List derivation is the Python Foundation, easy to use, but also very important function, is one of the most popular Python features, can be said to master it is the basic standard of qualified Python programmers. In essence, the list can be deduced into a function that aggregates transformations and filtering functions, which convert a list to another list. Note that this is another new list, and the original list remains unchanged. See Example:
(1) cubic operation of each element in the list (transform function)
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [x * * 3 for X in a if x 2 = 0]
Print (b)
[8, 64, 216, 512, 1000]
It can be seen from the results of the selection of the words is to first filter the transformation, that is, the first screen out the elements do not meet the conditions, and then the transformation operation. You can add multiple filter criteria, such as cubic operations on elements that are greater than 5 and even, as shown in the following example:
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [x * * 3 for X in a if x 2 = 0 if x > 5]
Print (b)
[216, 512, 1000]
(3) combined with zipCombine the relative dues in the A,b two list to form a new list. For example, the list of x coordinates and the y-coordinate list forms the corresponding point coordinates [x, Y] list.
A = [1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
XY = [[x, Y] for x, y in Zip (A, b)]
Print (XY)
[[-1, 1], [-2, 2], [-3, 3], [-4, 4], [-5, 5], [-6, 6], [-7, 7], [-8, 8], [-9, 9], [-10, 10]]
(4) Support multilayer for loopConverts a nested list into a one-dimensional list.
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [J for I in A for j in I]
Print (b)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Python also has dictionary derivation, set derivation, and so on, and the list is used in the same way. The use of the list derivation is very extensive, from the actual experience, the use of list derivation is very high, but also quite useful. And for the list of multi-level for the loop, especially more than 3 or with complex filter conditions, sacrificing more readability, directly with a number of ordinary for the loop implementation can be, after all, the convenience of the implementation function is the first, more than a few lines of code more than a few lines.