Python list parsing and python Parsing
List parsing, mainly used to dynamically create a list
This article mainly describes the usage of combining lambda, map (), and filter () with list parsing statements.
The basic syntax for list Parsing is: [expr for iter_var in iterable]
The core of this statement is the for loop, which iterates all entries of the iterable object. The previous expr is applied to each member of the sequence. The final result value is the list generated by the expression.
1. Basic use
Here is an example.
Test in idle:
>>> [I for I in range (0, 8)]
[0, 1, 2, 3, 4, 5, 6, 7]
Specifically, I is the expr in the basic syntax and iter_val. In another way, let's perform an operation to multiply all the members by 2.
>>> [I * 2 for I in range (0, 8)]
[0, 2, 4, 6, 8, 10, 12, 14]
This is a list parsing statement written completely according to the basic syntax.
2. Add judgment conditions after the recycling statement
Extended version Syntax: [expr for iter_val in iterable if cond_expr]
We can also expand the List by adding some statements behind it to filter the list. For example, if we only need the number that can be divisible by 2 in this value
>>> [I for I in range (1, 8) if I % 2 = 0]
[2, 4, 6]
This statement is similar to filter, so we can also use the built-in filter function of python to obtain the same value.
>>> L = filter (lambda x: x % 2 = 0, range (1, 8 ))
>>> For I in l:
I
2
4
6
But I found no. There are some differences, because I did not directly print the list. Why? Because the return value of the filter is a generator and the generator is
If you cannot know all values, you can only obtain the next value through iteration.
3. map is used to achieve the same result as list parsing.
>>> Map (lambda x: x * 2, range (1, 8 ))
[2, 4, 6, 8, 10, 12, 14]
It can achieve the same effect as [x * 2 for x in range ()], but the latter is more efficient than map ().
4. Generate a Matrix
When you need to get a matrix of three rows and five columns, It is very simple:
>>> [(X, y) for x in range (0, 3) for y in range (0, 5)]
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4 ),
(1, 0), (1, 1), (1, 2), (1, 3), (1, 4 ),
(2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]
You can also find more references for list parsing in PEP 202.