# 用List Comprehensions创建复杂列表

2018年5月16日 / 409次阅读
Python

Python的语句很靠近我们说话，比如这个list comprehensions，有人翻译为列表生成器。但comprehension是理解的意思，没有生成的意思。通过list comprehensions，我们可以很轻松创建复杂列表，并且很好理解。

>>>
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = [x * x for x in range(10)]
>>> b
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>

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

>>>
>>> d = [x + y for x in 'abc' for y in 'xyz']
>>> d
['ax', 'ay', 'az', 'bx', 'by', 'bz', 'cx', 'cy', 'cz']
>>>

>>> d = [x + y for x in 'abc' if x == 'a' for y in 'xyz']
>>> d
['ax', 'ay', 'az']
>>>
>>> d = [x+y for x in 'abc' for y in 'xyz' if x == 'a']
>>> d
['ax', 'ay', 'az']
>>>

if条件判断放在中间和后面都是一样的。

Python官方的一段说明：

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

List comprehension只有for和if。

### 留言区

《用List Comprehensions创建复杂列表》有2条留言

• 麦新杰

需要理解的List创建方式。 []

• 麦新杰

List Comprehension = listcomp []

Ctrl+D 收藏本页