List comprehensions, which is a very, very simple but most commonly used feature in Python.
As you can tell by name, the list generation should return the list type, which will generate the required lists in the simplest and most understandable notation.
Example: I need to get a list of 1-100 of the squares of all the numbers in this list. You can use a for loop at this point:
Python code
A = [] for value in range (1, 101): a.append (Value * value) print (a)
At this point A is an array of squares of each number in 1-100. This method is simple, but using list generation is simpler.
Python code
A = [value * value for value in range (1,101)] print (a)
The obtained a is the same as the one in the previous method.
In a = [value * value ' for value ' in range (1,101)], value * value is an expression, value this number is derived from the for loop after the expression, the For loop evaluates the expression once per loop, and finally the For loop The calculation results of the number of each loop are saved in a list. Finally assign a value to a.
You can also use multiple loops in a list build. For example :
Python code
A = [x * y for x in range (1,3) for Y in range (3,5)] print (a)
The resulting result is:
Terminal code
[3, 4, 6, 8]
Range (1,3) is [1, 2], range (3,5) is [3,4],x from range (1,3), Y from range (3,5)
The results were: 1*3, 1*4, 2*3, 2*4
In addition, you can add conditional judgments in the list-generation:
Python code
A = [value * value for value in range (1, one) if value% 2 = = 0] print (a)
#结果为:
[4, 16, 36, 64, 100]
Adds a conditional selection to the value after the for loop. This example calculates the square of an even number in 1-10