List comprehensions, namely List Comprehensions, are very simple but powerful built-in comprehensions in Python that can be used to create lists.
For example, to generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] you can use list(range(1, 11)):
list(range(1,11))[1,2,3,4,5,6,7,8,9,10]
But if you want to generate [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
How to do it? One way is to loop, but the loop is too cumbersome, and the list generation can use a line statement instead of loop to generate the above list:
[ x * x for x inrange(1,11)][1,4,9,16,25,36,49,64,81,100]
When writing a list production, put the elements to be generated x*Put x in the front, followed by a for loop, and you can create a list
An if judgment can be added after the for loop, so that we can filter out only even squares:
[ x * x for x inrange(1,11)if x %2==0][4,16,36,64,100]
You can also use a two-level loop to generate a full arrangement:
[ m + n for m in'ABC'for n in'XYZ']['AX','AY','AZ','BX','BY','BZ','CX','CY','CZ']
List generation can also use two variables to generate a list:
d ={'x':'A','y':'B','z':'C',}[k +'='+ v for k, v in d.items()]['y=B','x=A','z=C']
Recommended Posts