List parsing and expression generation in python

  • 2020-04-02 09:28:31
  • OfStack

List of analytical

Use list resolution when you need to change a list instead of creating a new one. The list parsing expression is:

[expr for iter_var in iterable] [expr for iter_var in iterable if cond_expr]
The first syntax is to iterate over everything in iterable, with each iteration placing the corresponding content in iterable in iter_var, then applying the iter_var content in the expression, and finally generating a list with the evaluated value of the expression.
The second syntax: add the judgment statement, only the content that satisfies the condition will put the corresponding content in iterable into iter_var, and then apply the content of iter_var in the expression, and finally generate a list with the evaluated value of the expression.

Examples are as follows:
 
>>> L= [(x+1,y+1) for x in range(3) for y in range(5)] 
>>> L 
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)] 
>>> N=[x+10 for x in range(10) if x>5] 
>>> N 
[16, 17, 18, 19] 

Generator expression

Generator expressions were introduced in python2.4, and when the sequence is too long and you only need to get one element at a time, you should consider using generator expressions instead of list parsing. The syntax for the generator expression is the same as for list parsing, except that the generator expression is enclosed by () instead of [], as follows:
 
(expr for iter_var in iterable) 
(expr for iter_var in iterable if cond_expr) 

Ex. :
 
>>> L= (i + 1 for i in range(10) if i % 2) 
>>> L 
<generator object <genexpr> at 0xb749a52c> 
>>> L1=[] 
>>> for i in L: 
... L1.append(i) 
... 
>>> L1 
[2, 4, 6, 8, 10] 

Instead of actually creating a list of Numbers, the generator expression returns a generator that "yields" the entry one at a time. Generator expressions use "lazy evaluation" (also translated as "lazy evaluation") and are evaluated only when retrieved, so it is more efficient to use memory when the list is long. A generator object in python is something like A lazy list. The elements are only evaluated as soon as you iterate over them.

Some notes:

1. Use loops instead of list parsing when you just need to execute a loop, which is more in line with python's intuitive approach.
 
for item in sequence: 
process(item) 

2. Do not use list resolution when there are built-in operations or types that can be implemented in a more straightforward manner.

For example, when copying a list, use: L1=list (L) instead of:
 
L1=[x for x in L] 

3. If you need to call each element and return the result, use L1=map(f,L) instead of L1=[f(x) for x in L]

Related articles: