The Python tricks you Don't know: 13 tricks [Practical] And python13 tricks
Sometimes you will see Cool Python code. You are surprised by its conciseness and elegance. You can't help but admire it: you can write it like this. In fact, all these elegant codes are attributed to the characteristics of Python. As long as you can master these Pythonic skills, you can write Python code like poetry.
1. Import Module
Do you often feel a headache when you enter a long string of module indexes when calling a module? To be honest, when the number is small, it may be tolerable. Once the scale of the program goes up, it is also a project that cannot be underestimated.
#Badimport urllib.requesturl = r'http://www.landsblog.com'req = urllib.request.Request(url)response = urllib.request.urlopen(req)#Goodform urllib import request url = r'http://www.landsblog.com'req = request.Request(url)response = request.urlopen(req)
Does this save some time?
But how can we solve the problem of duplicate module names due to such short expressions?
from module_a import fun as a_funfrom module_b import fun as b_fun
This method is also applicable to modules with long module names. What impressed me most is the BeautifulSoup module.
from bs4 import BeautifulSoup as BShtml = '''
Save time and effort.
2 "_"##
This is a very useful feature, but few people know it.
You can use "_" to obtain the Last Temporary result when you knock on the code on the interactive interface to obtain a temporary result without using the variable name to save it.
>>> 1 + 12>>> _2
Store the final output value in. This is very useful in interactive mode. When you do not save the computing result in the process, or you want to see the output result of the last step.
3. Merge strings
This is a conventional issue. When we need to merge several strings, we use "+" as a method to connect strings.
However, since the immutable object cannot be modified after it is generated in the memory, the merged string will re-open up a memory space for storage. In this way, the memory is quickly exhausted like a snowball.
# Badstring = ['a','b','c','d','e','f','g','h']def fun(string): all_string = '' for i in string: all_string += i return all_string# Goodstring = ['a','b','c','d','e','f','g,'h']def fun(string): all_string = ''.join(string) return all_string
4. Powerful zip ()
It is a Python built-in function. The zip function accepts any number of (including 0 and 1) sequences as parameters and returns a list containing tuple. The zip () function simplifies your code in many scenarios.
Transpose columns of a Matrix
# Bada = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]re_a = [[row[col] for row in a] for col in range(len(a))]>>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]# Gooda = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]re_a = list(zip(*a))>>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Exchange dict key values
# Bada = {'a': 1, 'b': 2, 'c': 3, 'd': 4}def reverse_dict(a): new_dict = {} for k,v in m.items(): new_dict[v] = k return new_dict# Gooda = {'a': 1, 'b': 2, 'c': 3, 'd': 4}def reverse_dict(a): k = a.keys() v = a.values() new_dict = dict(zip(v, k)) return new_dict
Merge list adjacent items
a = [1, 2, 3, 4, 5, 6]list(zip( a[::2], a[1::2] ))>>> [(1, 2), (3, 4), (5, 6)]
5. variable value exchange
# Badtmp = aa = bb = tmp#Gooda, b = b, a
6. Obtain the index (array subscript) in a loop )?
a = [8, 23, 45, 12, 78]for index, value in enumerate(a):print(index , value)
7. How can I capture multiple exceptions in only one row?
try: passexcept (ExceptionA,ExceptionB,.....) as e: pass
8. Split the list into blocks of the same size?
a = [1, 2, 3, 4, 5, 6]list(zip( *[iter(a)]*2 ))>>> [(1, 2), (3, 4), (5, 6)]
9. How do I find the subscript of an element in the list?
a = ['a', 'b', 'c', 'd', 'e', 'f']a_i = a.index(a)>>> 0
10. How to quickly reverse a string?
#Bada = 'Python is a powerful languange.'list_a = list(a)list_a.reverse()re_a = ''.join(list_a) #Gooda = 'Python is a powerful languange.'re_a = a[::-1]
11. Numerical Comparison
x = 2if 1< x <3: print(x)>>> 2if 1< x >0: print(x)>>> 2
12. Open files elegantly
When you use stream objects similar to files, you must call the close method to close them after they are used. With... The as statement provides a very convenient alternative: open the file, assign the returned file stream object to f, and then use it in the with statement block. After the with statement block is completed, the file is automatically closed hidden.
with open('nothing.txt','r') as f: f.read()
13. Say goodbye to your memory
crash = dict(zip(range(10 **0xA), range(10 **0xA)))
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!