1. List Resolution:
Listing parsing, list comprehensions, derived from the functional programming language Haskell, is a very useful, simple and flexible tool that you can use to create lists dynamically.
Syntax for list parsing:
[Expr for Iter_var in iterable]
Although the built-in function map () and filter (), lambda, and so on in Python support functional programming features, list parsing expressions can replace the built-in functions and lambda, and are more efficient.
For example, generate some square numbers.
You can use the map () and the lambda:
>>> Map (Lambda x:x * * 2, RANGE (10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
You can also use list resolution to replace:
>>> [x * * 2 for X in range (10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Using list resolution, only one call to range (), and the previous statement has three function calls (range (), map (), and Lambda).
In addition, list parsing also provides a filter condition, plus an IF statement:
[Expr for Iter_var in iterable if COND_EXPR]
For example, filter the square of the surprising number:
>>> Filter (lambda x: (x 2) * * 2, seq)
[1, 9, 25, 49, 81]
You can also use list parsing to complete:
>>> [x * * 2 for X in range (ten) if x 2]
[1, 9, 25, 49, 81]
You can also use list resolution for nested loops:
>>> [(X+1,Y+3) for x in range (2) for Y in range (3)]
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
There are many more examples to cite.
2. Builder expression:
A builder expression is an extension of list resolution. The disadvantage of list resolution is that you need to generate all the data to create the entire list, which consumes more memory space in the event of a large amount of data.
The builder expression solves the whole problem by combining list resolution and builder.
The builder is a specific function that allows you to return a value and then "pause" the execution of the code, resume later, and use the keyword yield.
The builder expression, instead of actually creating the list, returns a generator that uses deferred computations to make memory use more efficient.
Syntax format:
(Expr for Iter_var in iterable if cond_expr)
The builder expression is similar to the list resolution format, except that the generator expression returns a generator.
>>> g = (x * * 2 for X in range (10))
>>> g
<generator Object <genexpr> at 0x01aa7f80>