天天看點

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