Preface Here are some of the details I encountered during the development process. With June mutual encouragement.
Copyright Noticecopyright belongs to all authors.
Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Coding-naga
Links:http://blog.csdn.net/lemon_tree12138/article/details/50736887
Source: CSDN
1.Python for full alignment
Programme one:
A = [1, 2, 3, 4, 5, 6, 7, 8, 9]result = List (Itertools.permutations (A, 9))
Scenario Two:
Above is the built-in function using Python itertools.permutations is amazing for the full permutation speed of just 9 elements.
Let's say we write our own full-array logic, which can be the following:
# get full permutation listdef full_permutation (l): if (len (l) <= 1): return [l] r = [] for I in range (l En (L)): s = l[:i] + l[i + 1:] # Assigns the first three entries of L and the string after the i+1 of L to s p = full_permutation (s) for X in P: r.append (l[i: i + 1] + x) return R
All in the project or it is recommended to use the Python built-in full-array function, the second parameter can be 1-9 or whatever an integer, very convenient.
2. Traverse all subfolders and files under the folder? In Python, it is very convenient to iterate through the file folders. Check the files and folders, code such as the following:
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 ' fi Le: ' + os.path.join (parent, file_name)
3. Binary Conversions for strings? Assuming you have programming skills in other languages, you may already be familiar with the conversion process. It's just what I'm going to say here. The conversion is not a simple conversion from decimal to binary or into a 16-based system. Here are some of the things you can try to solve:
? A. Turn the hexadecimal number of a = ' ff ' to decimal 255
? B. Turn the decimal number of a = 14 into a 16 binary 0e
Workaround:
? A. It is necessary to specify the number of the original binary
decstr = Int (A, 16)
? B. A slicing operation is required to remove the prefix ' 0x '
Decstr = Hex (a) [2:]
If Len (decstr)% 2 = = 1:
? ? Decstr = ' 0 ' + decstr
4.IP Conversion between point and shaping numbers? Import two modules first: socket and struct
? 1. Convert ip1 = ' 172.123.156.241 ' to IP2 = 2893782257L
? ? IP2 = Socket.ntohl (Struct.unpack ("I", Socket.inet_aton (ip1)) [0])
? 2. Convert ip2 = 2893782257L to ip1 = ' 172.123.156.241 '
? ? IP1 = Socket.inet_ntoa (Struct.pack (' I ', socket.htonl (IP2)))
5.Python getting output information from the Linux console? There are two ways to solve problems, such as the following:
? Method One:
Import Subprocessimport osoutput = Os.popen (' cat/proc/cpuinfo | grep model ') print output.read ()
? Method Two:
Status, model = Commands.getstatusoutput (shell) print model
6. Use the enumerate () function to get the index and value of a sequence iteration
? Sometimes we iterate over the sequence, not just to know the values in the sequence, but also to know where the value is in the sequence.
? Suppose you want to use code implementations. It's not hard indeed. It just seems redundant, because Python has done this for us. For example, the following:
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 and ++i are different .
? We know that the self-increment operation is not supported in Python. So, do you think the ++i here will throw a grammatical error?
? Unfortunately, this does not throw a syntax error.
This is a problem for i++, but not for ++i. In the Pycharm editor, for example, we can see the following:
??
? In the illustration above. We can see that Pycharm throws an error to a++, which is a warning for ++a.
? The reason is in Python. ++a is considered to be + (+A), that is, "+" is understood as a positive sign.
So, the result of ++a is still a. Similarly, the result of--a is also a.
8. Define outdated methods using deprecationwarning
? Python also has similar annotation methods in Java. Here we take an example of outdated annotations, such as the following code:
@DeprecationWarningdef TEST_DEP (name): print ("Hi,%s."% name)
? Unlike Java, outdated annotations are used in Python. The program terminates execution by throwing an exception. For example, the following:
??
9. Counting statistics using counter
? How do you count statistics on a list?
? Traverse, table, set, what else? However. These operations are not so elegant for python.
The following is a more elegant way to operate, using Python's own counter implementation.
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 results of the program execution can be seen as follows:
??
10. Accurately infer file types
? Suppose the exact type of a file is inferred? The types described here are: PNG, JPG, DOC, CSV, and so on.
? Do not say from the suffix of the file obtained.
Assuming this is really the case, there is no point in the matter. And. We know that in everyday development, the files we encounter are often not suffixes. How do you use suffixes to infer this time?
? But, original aim. The file headers of the same type of file are the same, and the headers of different types of files are different.
With this, you can infer different file types. The code is also very well written, such as the following:
Import struct# support file type # The purpose of the 16 binary string is to be able to know how many bytes the file header is. # The length of various file headers is different. Less then 2 characters long 8 characters def type_list_table (): return {"ffd8ff": "JPEG", "89504E47": "PNG", "47494638": "GIF", "49492a00": "TIFF", "424D": "BMP", "41433130": "CAD", "38425053": "Adobe Photoshop", " 7b5c727466 ":" Rich Text Format (RTF), "3c3f786d6c": "XML", "68746d6c3e": "HTML", "d0cf11e0": "MS Word /excel (Xls.or.doc) "," 5374616e64617264204a ":" MS Access (MDB) "," 4357530A ":" Flash data [swf] "}#------ -----------------------------------# # byte code to 16 binary string # #-----------------------------------------#d EF Bytes2hex (byte_array): num = Len (byte_array) hex_string = u "" For I in Range (num): t = u "%x"% Byte_arr Ay[i] If Len (t)% 2:hex_string + = u "0" hex_string + = t return Hex_string.upper () #----------- ------------------------------# # get file type # #-----------------------------------------#def File_type (file_name): File_reader = open (file_name, ' RB ') # must be binary read Type_li st = type_list_table () Type_label = ' unknown ' for value in Type_list.keys (): Num_of_bytes = Len (value)/2 # How many bytes must be read File_reader.seek (0) # Every time the read goes back to the file header, otherwise it will be read backwards hbytes = Struct.unpack_from ("B" * Num_of_bytes, File_reader.read (num_of_bytes)) # a "B" represents a byte Type_code = Bytes2hex (hbytes) if Type_code = = V Alue: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"
- Encountered in programming
Python code optimization and tips Note (i)