Reference: Effective Python. If you have time, you can purchase the original book
A: Key words
- Python: Refers to Python3. I use Python3.6
Two: coding style
Code style: www.python.org/dev/peps/pe… Annotation style: www.python.org/dev/peps/pe…
Pylint is a static analysis tool for Python source code that checks compliance with the PEP 8 style guide
www.pylint.org/ 2
You can download the Pylint plugin from PyCharm and the word Pylint is displayed in the lower left corner of the charm to check your code. Pylint checks very strictly:
[
Image1371 x 923 152 KB
] (ceshiren.com/uploads/def…).
Three: encoding
Python3 has two character sequences: STR and bytes, where instances of bytes are bytes, which correspond to 8-bit binary data, and instances of STR contain Unicode characters, which can be converted to binary data using UTF-8 encoding, and vice versa. Python3 uses encode() and decode() for the above operations respectively:
Internally, Unicode is recommended, converting any external input to Unicode and bytes for external output. This ensures that the external encoding does not affect internal use and that the output is stable (both bytes). The following code implements binary and Unicode interconversion:
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value # Instance of bytes
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value # Instance of str
Copy the code
Python’s open() method uses encoding() by default, which requires a Unicode character to be passed, and it converts it to binary. If you pass binary data, an error will be reported
Os.urandom () produces a random bytes value, which is an error if written to the random.bin file, referring to the following code and output:
def main():
with open('./random.bin', 'w') as f:
f.write(os.urandom(15))
if __name__ == '__main__':
main()
Copy the code
[
Image893 30.7 x 217 KB
] (ceshiren.com/uploads/def…).
The following is a note from the official source:
In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding.
Just change the write mode to binary write:
```python
def main():
with open('./random.bin', 'wb') as f:
f.write(os.urandom(15))
if __name__ == '__main__':
main()
Copy the code
Four: auxiliary functions
Python has many powerful features that, if overused, can make code obscure. Consider the following code and return the result:
from urllib.parse import parse_qs
my_values=parse_qs('red=5&blue=0&green=',
keep_blank_values=True)
print(repr(my_values))
>>>
{'red': ['5'], 'blue': ['0'], 'green': ['']}
Copy the code
All three colors return values, and when you get the content with the get() method, you type the following:
print('Red: ', my_values.get('red'))
print('Green: ', my_values.get('green'))
print('xxxx: ', my_values.get('xxxx'))
>>>
Red: ['5']
Green: ['']
xxxx: None
Copy the code
Get returns null if the original list is empty, and None if the original key does not exist (such as XXXX). Now use Python to optimize the above code. Python hollow strings, empty lists, and zero values are False:
# to optimize a print (' Red: 'my_values. Get (' Red', [...]) [0] or 0) print (' Green: ', my_values.get('green', ['])[0] or 0) # print(' XXXX: ', my_values. Get (" XXXX ", [...]) [0] or 0) > > > Red: 5 Green: XXXX: 0 0 # to optimize two read = my_values. Get (' Red ', [...]) print (' Red: ', read[0] if read[0] else 0)Copy the code
Optimizations one and two keep the code small but complex. It is better to compromise the features and use the traditional if/else syntax to encapsulate the desired functionality in a function called helper:
def get_first_int(value: dict, key, default=0):
found = value.get(key, [''])
if found[0]:
found = found[0]
else:
found = default
return found
print('Red: ', get_first_int(my_values, 'red'))
Copy the code
Five: cut the sequence
Python slits a sequence, basically written as a list[start:end], where the elements referred to by start are in the cut range and the elements referred to by end are not included in the cut result. Look at the following code and the output:
a = ['a','b','c','d','e','f','g','h','i']
print('First four:',a[:4])
print('last four:',a[-4:])
print('Middle three:',a[3:-3])
>>>
First four: ['a', 'b', 'c', 'd']
last four: ['f', 'g', 'h', 'i']
Middle three: ['d', 'e', 'f']
Copy the code
Start and end can be used out of bounds, so you can limit the maximum length of the input sequence, for example, to 20:
a=['a', 'v', 'c']
print(a[:20])
print(a[-20:])
>>>
['a', 'v', 'c']
['a', 'v', 'c']
Copy the code
Anything done to the cut content will not affect the original list, such as:
a=['a', 'v', 'c']
b=a[1:]
b[0]=10
print('a: ' , a)
print('b: ', b)
>>>
a: ['a', 'v', 'c']
b: [10, 'c']
Copy the code
You can expand the list by replacing the specified range of values in the list with new values, for example:
a1 = ['a', 'v', 'c', 'h']
a1[0:10]=['f','f']
print('a1: ', a1)
a2 = ['a', 'v', 'c', 'h']
a2[2:3]=['f','f']
print('a2: ', a2)
>>>
a1: ['f', 'f']
a2: ['a', 'v', 'f', 'f', 'h']
Copy the code
Six: single slice does not specify start, end and stride at the same time
Somelist [start:end:stride] somelist[start:end:stride] somelist[start:end:stride]
a = ['i','love','hogwarts','every','day']
odds = a[::2]
evens = a[1::2]
print(odds)
print(evens)
>>>
['i', 'hogwarts', 'day']
['love', 'every']
Copy the code
It can even be reversed:
a = ['i', 'love', 'hogwarts', 'every', 'day']
b = b'abcdefgh'
reverse_a = a[::-1]
reverse_b = b[::-1]
print(reverse_a)
print(reverse_b)
>>>
['day', 'every', 'hogwarts', 'love', 'i']
b'hgfedcba'
Copy the code
This technique works for both bytes and ASCII characters, and causes problems for Unicode encoded as UTF-8 bytes:
C = c [::-1] d = c print(d) >>> Traceback (most recent call last) File "xxx", line 5, in <module> d = c.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa2 in position 0: invalid start byteCopy the code
In addition, the meanings of 2::2, -2::-2, -2:2:-2 and 2:2:-2 are the same. If there are too many parameters, the meaning will be very difficult to understand, and the stride, start and end should not be written together. Positive stride is adopted as far as possible, and start and end indexes are omitted. If you must use the stride with the start or end index, you can step the slice first, assign the cutting result to the variable, and then cut on the variable. You can also use islide, which does not allow start, end, or stride to have negative values.
a = ['i','love','hogwarts','every','day']
b = a[::2]
c = b[1:-1]
print(c)
>>>
['hogwarts']
Copy the code
Seven: Derivation formula
Python can make a list from another list, including dict, using the following code and the result:
a = ['i','love','hogwarts','every','day']
b1 = [k+'ff' for k in a]
b2 = [k+'ff' for k in a if k == 'every']
print('b1: ',b1)
print('b2: ',b2)
>>>
b1: ['iff', 'loveff', 'hogwartsff', 'everyff', 'dayff']
b2: ['everyff']
Copy the code
Of course, map and filter can do the same, but it’s hard to understand. Dictionaries and sets have a similar derivation mechanism, as shown below:
a = {'a': 'i', 'b': 'love', 'c': 'hogwarts', 'd': 'every', 'e': 'day'}
b1 = {key:value+'ff' for key, value in a.items()}
b2 = {key:value+'ff' for key, value in a.items() if key == 'd' or key == 'a'}
print('b1: ', b1)
print('b2: ', b2)
>>>
b1: {'a': 'iff', 'b': 'loveff', 'c': 'hogwartsff', 'd': 'everyff', 'e': 'dayff'}
b2: {'a': 'iff', 'd': 'everyff'}
Copy the code
Do not use list derivations with more than two expressions
todo
More technical articles can be found at qrcode.testing-studio.com/f?from=juej…