list comprehension

 


List comprehensions, or List Comprehensions, are very simple but powerful built-in comprehensions in Python 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 generate [1x1, 2x2, 3x3, ..., 10x10]it? The first method is to 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 comprehension can replace the loop with one line to generate the above list:

>>> [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 

When writing a list comprehension, put the elements to be generated in the x * xfront, followed by a forloop, and you can create a list. It is very useful. After writing it a few times, you can quickly become familiar with this syntax.

You can also add an if judgment after the for loop, so that we can filter out only even squares:

>>> [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100] 

It is also possible to use a two-layer loop, which can generate a full permutation:

>>> [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] 

Loops with three or more layers are rarely used.

Using list comprehensions, you can write very concise code. For example, listing all files and directory names in the current directory can be done with 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'] 

forThe loop can actually use two or more variables at the same time, for example dict, iteritems()it can 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 = B x = A z = C 

Therefore, a list comprehension can also use two variables to generate a list:

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' } >>> [k + '=' + v for k, v in d.iteritems()] ['y=B', 'x=A', 'z=C'] 

Finally convert all strings in a list to lowercase:

>>> L = ['Hello', 'World', 'IBM', 'Apple'] >>> [s.lower() for s in L] ['hello', 'world', 'ibm', 'apple'] 

 

Using list comprehensions, you can quickly generate lists, and you can deduce another list from one list, but the code is very concise.

Thinking: If the list contains both strings and integers, since there is no lower()method for non-string types, the list comprehension will report 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 built-in isinstancefunctions to determine whether a variable is a string:

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str) True >>> isinstance(y, str) False

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324668788&siteId=291194637