I. List resolution (list push-down):
Function: is to provide a convenient list creation method, so the list parsing returns a list.
LST = [1, 3, 5, 8, 10]
ll = [x+x for x in LST if x <= 5]
Print LL
>>>[2, 6, 10]
two. Dictionary parsing style:
DIC = {' A ': 1, ' B ': 2, ' C ': 3}
D = {k:v for k, V in Dic.items () if v >=2}
Print D
>>>{' C ': 3, ' B ': 2}
three. Set Analytic type:
The use of Set deduction and list derivation is similar, except that the brackets should be changed to curly braces.
LST = [1, 3, 5, 8, 10]
AA = {x+x for x in LST if x <= 5}//Note Set parsing uses curly braces!!!
Print AA
>>>set ([2, 10, 6])//and output as a collection!!!
four. Generator:
With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, create a 1 million-element
The list of elements, not only takes up a lot of storage space, if we just need to access the previous elements, then the vast majority of the space occupied by the element is wasted.
So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create
The whole list, thus saving a lot of space. In Python, this side loop computes the mechanism, called the Generator (Generator).
Python offers two ways to create generators:
① Generator Function: defined as regular functions, but with yield instead of return.
Yeild will return one result at a time, then hang, and continue execution the next time it is suspended, which resolves the memory limit.
Note: Other methods perform all of the results at once, and then return one result at a time, so that if the amount of data is large, it will be limited by memory and will consume a large
Storage space.
Def gen (n):
For I in range (n):
Yeild i + 2
For item in Gen (10):
Print Item
② Generator Build:
Similar to the list generation, except that square brackets are replaced with brackets.
Generators = (x+2 for x in range (10))
Python list parsing, dictionary parsing, set parsing, and generators