天天看点

python comprehension_python – “list comprehension”是什么意思?它如何工作,如何使用它?...

From the documentation:

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

关于你的问题,列表解析和下面的“plain”Python代码做同样的事情:

>>> l = []

>>> for x in range(10):

... l.append(x**2)

>>> l

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

你怎么写在一行?嗯…我们可以…可能…使用map() with lambda:

>>> list(map(lambda x: x**2, range(10)))

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

但是使用列表解析不是更清楚和更简单吗?

>>> [x**2 for x in range(10)]

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

基本上,我们可以做任何事情与x。不仅x ** 2。例如,运行x的方法:

>>> [x.strip() for x in ('foo\n', 'bar\n', 'baz\n')]

['foo', 'bar', 'baz']

或者使用x作为另一个函数的参数:

>>> [int(x) for x in ('1', '2', '3')]

[1, 2, 3]

例如,我们还可以使用x作为dict对象的键。让我们来看看:

>>> d = {'foo': '10', 'bar': '20', 'baz': '30'}

>>> [d[x] for x in ['foo', 'baz']]

['10', '30']

如何组合?

>>> d = {'foo': '10', 'bar': '20', 'baz': '30'}

>>> [int(d[x].rstrip('0')) for x in ['foo', 'baz']]

[1, 3]

等等。

你也可以在列表推导中使用if或if … else。例如,您只需要在范围(10)中的奇数。你可以做:

>>> l = []

>>> for x in range(10):

... if x%2:

... l.append(x)

>>> l

[1, 3, 5, 7, 9]

啊太复杂了。以下版本怎么样?

>>> [x for x in range(10) if x%2]

[1, 3, 5, 7, 9]

要使用if … else三元表达式,您需要将if … else …放在x之后,而不是在range(10)之后:

>>> [i if i%2 != 0 else None for i in range(10)]

[None, 1, None, 3, None, 5, None, 7, None, 9]

你听说过nested list comprehension了吗?你可以把两个或多个fors放在一个列表解析中。例如:

>>> [i for x in [[1, 2, 3], [4, 5, 6]] for i in x]

[1, 2, 3, 4, 5, 6]

>>> [j for x in [[[1, 2], [3]], [[4, 5], [6]]] for i in x for j in i]

[1, 2, 3, 4, 5, 6]

让我们来讨论第一部分,对于[[1,2,3],[4,5,6]]中的x,给出[1,2,3]和[4,5,6]。然后,对于i in x给出1,2,3和4,5,6。

警告:在i in x之前,您总是需要为[[1,2,3],[4,5,6]]中的x放置:

>>> [j for j in x for x in [[1, 2, 3], [4, 5, 6]]]

Traceback (most recent call last):

File "", line 1, in

NameError: name 'x' is not defined

我们还设置了comprehensions,dict comprehension和generator表达式。

集合理解和列表理解基本上是一样的,但前者返回一个集合而不是一个列表:

>>> {x for x in [1, 1, 2, 3, 3, 1]}

{1, 2, 3}

它是相同的:

>>> set([i for i in [1, 1, 2, 3, 3, 1]])

{1, 2, 3}

A dict comprehension看起来像一个集合的理解,但它使用{key:value为key,value in …}或{i:i for i in …},而不是{i for i in …}。

例如:

>>> {i: i**2 for i in range(5)}

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

它等于:

>>> d = {}

>>> for i in range(5):

... d[i] = i**2

>>> d

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

是否(i对于i在范围(5))给一个元组?不,它是一个generator expression.它返回一个生成器:

>>> (i for i in range(5))

at 0x7f52703fbca8>

它是相同的:

>>> def gen():

... for i in range(5):

... yield i

>>> gen()

你可以使用它作为一个发电机:

>>> gen = (i for i in range(5))

>>> next(gen)

>>> next(gen)

1

>>> list(gen)

[2, 3, 4]

>>> next(gen)

Traceback (most recent call last):

File "", line 1, in

StopIteration

注意:如果在函数中使用列表推导,那么如果该函数可以在一个生成器上循环,则不需要[]。例如,sum():

>>> sum(i**2 for i in range(5))

30