Record elegant pythonic code and pythonic code
Record some pythonic methods that are commonly used in learning and seen on the Internet, which is only convenient for future queries.
1. List derivation:
seq_list=[1,2,3,4,5]new_list=[i *2 for i in seq_list if i %2==0 ]
2. Generator expression (reduce memory usage)
seq_list=(i*2 for i in range(0,1000) )
3. Powerful built-in function zip, which can traverse two iteratable objects. It is particularly useful when converting rows into classes. (However, it seems that the speed of the zip function is slow when processing big data)
List_1 = [,] list_2 = [, 1] for element in zip (list_1, list_2) print (element)) # The extra elements in list_1 will be automatically ignored.
4. * used to deconstruct iteratable objects
When a function, such as person, needs to pass all the elements in the list person_list as parameters, you only need person (* person_list.
5. The parameter * args is used to define the number of parameters accepted by the function. All parameters are stored in the list named args.
Def person (* args): for name in args: print ("the person is % s" % name) ##################### person ('A', 'B', 'C', 'D ', 'E') # Example 1 names = ['A', 'B', 'C', 'D', 'E'] person (* names) # Use * to deconstruct the names list. For example, the person is Athe person is Bthe person is Cthe person is Dthe person is E
6. Context Manager
With open ('file', 'R') as fh: for line in fh. readlines (): print (line)
___________________________
Use with instead of using the method of adding fh. close () in the old version. When a with statement is used to read a file or an exception occurs in the middle of the process, the file is automatically closed. The fh. close () method does not close the file normally when an exception occurs (because the code stops midway through and cannot be executed to fh. close ())
7. progress bar Control
import sysimport timefor i in range(1,61): sys.stdout.write('#'+'->'+'\b\b') sys.stdout.flush() time.sleep(0.5)
8. List deduplication
a=[1,2,3,4,5,3,2,2,1]b=list(set(a))
9. Convert the nested list into a single list
a=[[1,2],[3,4],[5,6]]import itertoolsb=list(itertools.chain.from_iterable(a))
10. List Replication
List_a = [1, 2, 3] list_ B = list_a # This method does not implement replication, but list_a and list_ B point to the same memory, that is, the location where [1, 2, 3] is stored. Correct replication method: list_ B = list_a [:]