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 range(1, 11)
:
>>> 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 # 导入os模块,模块的概念后面讲到>>> [d for d in os.listdir(‘.‘)] # os.listdir可以列出文件和目录[‘.emacs.d‘, ‘.ssh‘, ‘.Trash‘, ‘Adlm‘, ‘Applications‘, ‘Desktop‘, ‘Documents‘, ‘Downloads‘, ‘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 iteritems()
ability to iterate key and value at the same time:
>>> d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ }>>> for k, v in d.iteritems():... 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.iteritems()][‘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‘]
Summary
By using the List Builder, you can quickly generate a list that can derive another list from a list, while the code is very concise.
Think: If the list contains both a string and an integer, because there is no method for the non-string type lower()
, the listing generates an error:
>>> L = [‘Hello‘, ‘World‘, 18, ‘Apple‘, None]>>> [s.lower() for s in L]Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: ‘int‘ object has no attribute ‘lower‘
Use the built-in isinstance
function to determine if a variable is a string:
>>> x = ‘abc‘>>> y = 123>>> isinstance(x, str)True>>> isinstance(y, str)False
Please modify the list generation by adding if
statements to ensure that the list generation is executed correctly.
Python List-generated