Super practical 10 Python cases
- 2021-12-04 19:18:01
- OfStack
In this article, we will introduce 30 short code snippets that you can understand and learn in 30 seconds or less.
1. Check for duplicate elements
The following method can check whether there are duplicate elements in a given list. It uses
set()
Property, which will remove duplicate elements from the list.
def all_unique(lst):
return len(lst) == len(set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True
2. Anaphoric words
Detects whether two strings are variable words for each other (that is, reverse the character order with each other)
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True
3. Check memory usage
The following code snippet can be used to check the memory usage of an object.
import sys
variable = 30
print(sys.getsizeof(variable)) # 24
4. Byte size calculation
The following method returns the string length in bytes.
def byte_size(string):
return(len(string.encode('utf-8')))
byte_size(' ') # 4
byte_size('Hello World') # 11
5. Repeat the string N
The following code prints a string n times without using a loop
n = 2;
s ="Programming"; print(s * n);
# ProgrammingProgramming
6. Capital initials
The following code snippet uses the
title()
Method capitalizes the first letter of each word in the string.
s = "programming is awesome"
print(s.title()) # Programming Is Awesome
7. Block
The following methods use the
range()
Block the list into smaller lists of the specified size.
from math import ceil
def chunk(lst, size):
return list(
map(lambda x: lst[x * size:x * size + size],
list(range(0, ceil(len(lst) / size)))))
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
8. Compress
The following methods use the
fliter()
Delete error values in the list, such as:
False
,
None
, 0 and "")
def compact(lst):
return list(filter(bool, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
9. Number of intervals
The following code snippet can be used to convert a 2-dimensional array.
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(transposed) # [('a', 'c', 'e'), ('b', 'd', 'f')]
10. Chain comparison
The following code can be compared multiple times with various operators in line 1.
a = 3
print( 2 < a < 8) # True
print(1 == a < 2) # False