The list generation, which is the comprehensions, is a very simple and powerful build of Python built-in that can be used to create lists.
For example, to generate a 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 what if you want to build [1x1, 2x2, 3x3, ..., 10x10]
? Method One is the loop:
>>> L = []>>> for x in range(1, 11):... L.append(x * x)...>>> L[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
But the loop is too cumbersome, and the list generation can use a line of statements instead of loops to generate the list above:
>>> [x * x for x in range(1, 11)][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
When writing list generation, put the elements to be generated in x * x
front, followed by the for
loop, you can create a list, very useful, write a few more times, you can quickly become familiar with this syntax.
The For loop can also be followed by an if judgment so that we can filter out only the even squares:
>>> [x * x for x in range(1, 11) if x % 2 == 0][4, 16, 36, 64, 100]
You can also use a two-layer loop to generate a full array:
>>> [m + n for m in ‘ABC‘ for n in ‘XYZ‘][‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘]
Three-and three-storey loops are rarely used.
Using a list-generated formula, you can write very concise code. For example, listing all the file and directory names in the current directory can be implemented in one line of code:
>>> import os # Import OS module, the concept of module is >>> [d for d in Os.listdir (# Os.listdir can list files and directories [ ' ADLM ', ' applications ', ' Desktop ', ' Library ', ' Movies ', ' Music ', ' Pictures ', ' public ', ' VirtualBox VMs ', ' Workspace ', ' XCode ']
for
Loops can actually use two or more variables at the same time, such as dict
the items()
ability to iterate key and value at the same time:
>>> d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ }>>> for k, v in d.items():... print(k, ‘=‘, v)...y = Bx = Az = C
As a result, list generators can also use two variables to generate lists:
>>> d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ }>>> [k + ‘=‘ + v for k, v in d.items()][‘y=B‘, ‘x=A‘, ‘z=C‘]
Finally, all the strings in a list are converted to lowercase:
>>> L = [‘Hello‘, ‘World‘, ‘IBM‘, ‘Apple‘]>>> [s.lower() for s in L][‘hello‘, ‘world‘, ‘ibm‘, ‘apple‘]
Python List-generated