Python code optimization and tips (1)
Preface here we will record some of the detailed problems I encountered during the development process and share them with you. 1. Complete Python Arrangement
Solution 1:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]result = list(itertools.permutations(a, 9))
Solution 2:
The above uses the python built-in function itertools. permutations to speed up the full arrangement of only nine elements.
If we write the full arrangement logic by ourselves, it can be as follows:
# Get full permutation listdef full_permutation (l): if (len (l) <= 1): return [l] r = [] for I in range (len (l )): s = l [: I] + l [I + 1:] # assign the first three items of l and the strings after I + 1 to s p = full_permutation (s) for x in p: r. append (l [I: I + 1] + x) return r
We recommend that you use the Python built-in Full Permutation function in the project. The second parameter can be an integer between 1 and 9, which is very convenient. 2. traverse all subfolders and files in a folder. in Python, you can easily traverse the file directories cyclically and check the files and directories. The Code is as follows:
import osimport os.pathdef cycle_visiting(root_dir=None): for parent, folder_names, file_names in os.walk(root_dir): for folder_name in folder_names: print 'folder: ' + folder_name for file_name in file_names: print 'file: ' + os.path.join(parent, file_name)
3. If you have programming skills in other languages for String Conversion, you may be familiar with conversion. However, the hexadecimal conversion I want to talk about here is not simply converting from decimal to binary or to hexadecimal. Below you can try to solve the following problems:
A. Convert the hexadecimal number of a = 'ff 'to 255 in decimal format.
B. Convert the decimal number of a = 14 to the 0e in hexadecimal format.
Solution:
A. here we need to use a parameter to specify the original hexadecimal number.
Decstr = int (a, 16)
B. here we need to use a slicing operation to remove the prefix '0x'
Decstr = hex (a) [2:]
If len (decstr) % 2 = 1:
The conversion between decstr = '0' + decstr4.IP's vertex classification and Integer Conversion requires two modules: socket and struct.
1. Convert ip1 = '127. 123.156.241 'to ip2 = 2893782257L
Ip2 = socket. ntohl (struct. unpack ("I", socket. inet_aton (ip1) [0])
2. Convert ip2 = 2893782257L to ip1 = '2017. 123.156.241'
Ip1 = socket. inet_ntoa (struct. pack ('I', socket. htonl (ip2) 5. python can solve this problem by obtaining the output information in the Linux console in two ways:
Method 1:
import subprocessimport osoutput = os.popen('cat /proc/cpuinfo | grep model')print output.read()Method 2:
status, model = commands.getstatusoutput(shell)print model
6. Use the enumerate () function to obtain the index and value of the sequential iteration.
Sometimes when we iterate on a sequence, we not only need to know the value in the sequence, but also the position of the value in the sequence.
It is indeed not difficult to use code for implementation. But it seems redundant, because Python has already done this for us. As follows:
def test_enumerate(): array = [1, 2, 3, 4, 5, 6] for index, data in enumerate(array): print("%d: %d" % (index, data)) e = enumerate(array) print(e.next()) print(e.next()) print(e.next())7. I + = 1 is different from ++ I
We know that Python does not support auto-increment operations. So, do you think ++ I will throw a syntax error?
Unfortunately, syntax errors are not thrown here. This is indeed a problem with I ++, but not with ++ I. For example, in the PyCharm Editor, we can see the following phenomena:
In the preceding figure, we can see that PyCharm throws an error message for a ++ and a warning for ++.
The reason is that in Python, ++ a is regarded as ++ (+ a), that is,"+"It is understood as a positive symbol. Therefore, the result of ++ a is still. Similarly, the result of -- a is also.
8. Use DeprecationWarning to define an out-of-date Method
Python also has annotation methods similar to those in Java. Here we take the outdated annotation as an example. The Code is as follows:
@DeprecationWarningdef test_dep(name): print("Hi, %s." % name)
Different from Java, the program stops running when an exception is thrown using outdated annotations in Python. As follows:
9. Count statistics using Counter
How does one count a list?
Traverse, create tables, and set. What else? However, these operations are not so elegant for Python. The following is an elegant operation method that uses the Counter implementation provided by Python. The Code is as follows:
from collections import Counterdef get_counter(data): print(data) print(Counter(data))if __name__ == '__main__': get_counter(['d', 'a', 'd', 'a', 's', 'e', 'f', 'h', 'w', 'e', 'q', 'd', 'e', 'w', 'f', 's', 'd', 'a'])
The execution result of the program is as follows:
10. accurately determine the file type
What if I accurately determine the type of a file? The following types are described: png, jpg, doc, and csv.
Do not obtain it from the file suffix. If this is the case, it makes no sense. In addition, we know that in daily development, the files we encounter often have no suffixes. In this case, how can I use the suffix to determine the problem?
However, things cannot be different. The file headers of the same type of files are the same, and the headers of different types of files are different. Through this, we can determine different file types. The Code is also well written as follows:
Import struct # supports file types # The purpose of using a hexadecimal string is to know the number of bytes in the file header # The length of different file headers is not the same as that of two characters, the length is 8 characters. def type_list_table (): return {"FFD8FF": "JPEG", "89504E47": "PNG", "47494638": "GIF", "49347a00 ": "TIFF", "mongod": "BMP", "41433130": "CAD", "38425053": "Adobe Photoshop", "7B5C727466": "Rich Text Format (rtf) "," 3C3F786D6C ":" XML "," 68746D6C3E ":" HTML "," D0CF11E0 ":" MS Word/Excel (xls.or.doc) "," 5374616e64617426204a ": "MS Access (mdb)", "4357530A": "Flash data [swf]" }# ----------------------------------------- # convert bytecode to hexadecimal string # def bytes2hex (byte_array): num = len (byte_array) hex_string = u "" for I in range (num): t = u "% x" % byte_array [I] if len (t) % 2: hex_string + = u "0" hex_string + = t return hex_string.upper () # metadata # obtain the file type # metadata # def file_type (file_name): file_reader = open (file_name, 'rb') # type_list = type_list_table () type_label = 'unknown 'for value in type_list.keys (): num_of_bytes = len (value) /2 # How many bytes to read file_reader.seek (0) # Return to the file header for each read, otherwise hbytes = struct will continue to be read. unpack_from ("B" * num_of_bytes, file_reader.read (num_of_bytes) # A "B" indicates a byte type_code = bytes2hex (hbytes) if type_code = value: type_label = type_list [value] break file_reader.close () return type_labelif _ name _ = '_ main _': print file_type ('xxx/xxx.jpg ')Ref:
Writing high-quality code: 91 suggestions for improving Python programs