Note: the following tips are based on Python 3
Exchange variable value
a, b = 1, 2 print("Assignment:", a, b) # Exchange variable value a, b = b, a print("Exchange:", a, b)
Assignment: 1 2 Exchange: 2 1
Chain comparison
a = 5 print(1 < a < 10) print(5 < a < 10)
True False
String format f-Strings
# Python 3.6 starts to support name = "Jack" print(f"Hello {name}")
Hello Jack
Number of string splits
# For example, divide the url with "/", only once from the right side, to get the final path url = "http://www.test.com/page/page/12345" # Split once with "/" from the right result = url.rsplit('/', 1) print(result) # Take the second element print(result[1])
['http://www.test.com/page/page', '12345'] 12345
Get the last element in the list
a = [1, 2, 3] # Last element print(a[-1])
3
Remove duplicates from list
a = [1, 2, 4, 5, 5, 7, 4, 9] # duplicate removal a = list(set(a)) print(a)
[1, 2, 4, 5, 7, 9]
Reverse list
a = [1, 2, 3] # reversal b = a[::-1] print(b)
[3, 2, 1]
Number of statistical elements
from collections import Counter a = ['a','a','b','b','b','c','d','d','d','d','d'] count = Counter(a) print(count)
Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
Concatenate the list into a string with commas (or any other character)
a = ['a', 'b', 'c'] print(','.join(a))
a,b,c
Get element index on loop list
a = ['a', 'b', 'c'] for index,v in enumerate(a): print(index, v)
0 a 1 b 2 c
Get the same item in two lists
l1 = [1, 2, 3, 4, 5] l2 = [1, 2, 5, 6, 7, 8] l = list(set(l1) & set(l2)) print(l)
[1, 2, 5]
Get the first, last, and middle parts of the list
a = [1, 2, 3, 4, 5] first, *rest, last = a print(first) print(rest) print(last)
1 [2, 3, 4] 5
Converting a secondary list to a primary list
a = [[1, 2], [3, 4]] # Convert to first level list b = [x for _list in a for x in _list] print(b)
[1, 2, 3, 4]
Combine two linked lists into one list
l1 = [1, 2] l2 = [3, 4] # Method 1: merge the list into another list l3 = l1 + l2 print(l3) # Method 2: merge list 2 into List 1 l1.extend(l2) print(l1)
[1, 2, 3, 4] [1, 2, 3, 4]
Combine two lists into a dictionary
l1 = ['a', 'b', 'c'] l2 = [1, 2, 3] d = dict(zip(l1, l2)) print(d)
{'a': 1, 'b': 2, 'c': 3}
Dictionary sort by value
d = {"a": 3, "b": 4, "c": 2, "d": 1} reversed_d = sorted(d.items(), key=lambda item: item[1]) print(reversed_d)
[('d', 1), ('c', 2), ('a', 3), ('b', 4)]
Set default values in dictionary
d = {'a': 1, 'b': 2} # If not, set default d.setdefault('c', 3) print(d) # If it already exists, it will not be updated d.setdefault('b', 3) print(d)
{'a': 1, 'b': 2, 'c': 3} {'a': 1, 'b': 2, 'c': 3}
Dictionary get method
d = {'a': 1, 'c': 3} print(d.get('c', 33)) # get method. If the key does not exist, take the following default value print(d.get('b', 33))
3 33
Key inversion in dictionary
d = {1: 'a', 2: 'b', 3: 'c'} invert_d = {v: k for k, v in d.items()} print(invert_d)
{'a': 1, 'b': 2, 'c': 3}
Get common items in two dictionaries
d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'b': 4, 'c': 3, 'd': 6} # Common key print(d1.keys() & d2.keys()) # Common key value pair print(d1.items() & d2.items())
{'c', 'b'} {('c', 3)}
Merge two dictionaries into one
d1 = {'a': 1} d2 = {'b': 2} # Merge dictionary d3 = {**d1, **d2} print(d3)
{'a': 1, 'b': 2}
For else statement
for i in [1, 2, 3]: if i == 0: break else: print("Not implemented break")
break not performed
While-Else
i = 5 while i > 1: print(i) i -= 1 else: # Note: when there is a break in while, the following will not be executed in else. This is different from for else, which is worth noting print("End of cycle")
5 4 3 2 End of cycle
Try except else statement
In Python, you can simply use try exception statement to handle error exceptions. In fact, you can add an else statement, which refers to the statement that runs after the try statement is executed when no exception occurs. In addition, if you need to run code that needs to be executed to find exceptions, you can use finally, for example:
a, b = 1,2 try: print(a/b) except Exception as _: print(e) else: print("No exception occurred") finally: print("Execute whether or not an exception occurs")
0.5 No exception occurred Execute whether or not an exception occurs
Get current folder name
import os os.path.basename(os.getcwd())
'fun_of_python'
The above are some tips for sorting out. I hope they can help you. Welcome to make additional communication~