什么是“列表理解"?意思?它是如何工作的,我该如何使用它? [英] What does "list comprehension" mean? How does it work and how can I use it?

查看:36
本文介绍了什么是“列表理解"?意思?它是如何工作的,我该如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

当我在 Python shell 中运行它时,它返回:

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

我搜索过,似乎这被称为列表推导,但它是如何工作的?

解决方案

来自文档:

<块引用>

列表推导式提供了一种创建列表的简洁方法.常见的应用是创建新列表,其中每个元素都是应用于另一个序列或可迭代的每个成员的某些操作的结果,或者创建满足特定条件的那些元素的子序列.

<小时>

关于您的问题,列表推导式与以下纯"Python 代码的作用相同:

<预><代码>>>>l = []>>>对于范围内的 x(10):... l.append(x**2)>>>升[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

一行字怎么写?嗯...我们可以...可能...使用 map()lambda:

<预><代码>>>>列表(地图(拉姆达 x:x**2,范围(10)))[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

但是仅使用列表推导式不是更清晰、更简单吗?

<预><代码>>>>[x**2 代表范围内的 x(10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

<小时>

基本上,我们可以用 x 做任何事情.不仅仅是x**2.比如运行一个x的方法:

<预><代码>>>>[x.strip() for x in ('foo ', 'bar ', 'baz ')]['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]

等等.

<小时>

您还可以在列表推导式中使用 ifif...else.例如,您只需要 range(10) 中的奇数.你可以这样做:

<预><代码>>>>l = []>>>对于范围内的 x(10):...如果 x%2:... l.append(x)>>>升[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)][无,1,无,3,无,5,无,7,无,9]

<小时>

您听说过嵌套列表理解强>?您可以将两个或多个 for 放在一个列表推导式中.例如:

<预><代码>>>>[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]

先说第一部分,for x in [[1, 2, 3], [4, 5, 6]] 得到 [1, 2, 3][4, 5, 6].然后,for i in x 给出 123456.

警告:你总是需要把 for x in [[1, 2, 3], [4, 5, 6]] before> for i in x:

<预><代码>>>>[j for j in x for x in [[1, 2, 3], [4, 5, 6]]]回溯(最近一次调用最后一次):文件<input>",第 1 行,在 <module> 中NameError: 名称 'x' 未定义

<小时>

我们还有集合推导字典推导生成器表达式.

集合推导和列表推导基本相同,但前者返回一个集合而不是一个列表:

<预><代码>>>>{x 在 [1, 1, 2, 3, 3, 1]} 中的 x{1, 2, 3}

这与:

<预><代码>>>>set([i for i in [1, 1, 2, 3, 3, 1]]){1, 2, 3}

A 字典理解 看起来像一个集合推导式,但它使用{key: value for 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 = {}>>>对于范围内的 i (5):... d[i] = i**2>>>d{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

(i for i in range(5)) 是否给出了一个 元组?不!,这是一个生成器表达式.返回一个生成器:

<预><代码>>>>(i for i in range(5))<生成器对象<genexpr>在 0x7f52703fbca8>

这与:

<预><代码>>>>定义生成():...对于范围内的我(5):...屈服我>>>基因()<生成器对象 gen 在 0x7f5270380db0>

您可以将其用作生成器:

<预><代码>>>>gen = (i for i in range(5))>>>下一代)0>>>下一代)1>>>列表(gen)[2, 3, 4]>>>下一代)回溯(最近一次调用最后一次):文件<input>",第 1 行,在 <module> 中停止迭代

注意:如果您在函数内使用列表推导式,如果该函数可以循环,则不需要 []发电机.例如,sum():

<预><代码>>>>sum(i**2 for i in range(5))30

相关(关于生成器):了解 Python 中的生成器.

I have the following code:

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

When I run it in the Python shell, it returns:

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

I've searched and it seems this is called a list comprehension, but how does it work?

解决方案

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.


About your question, the list comprehension does the same thing as the following "plain" Python code:

>>> l = [] 
>>> for x in range(10):
...     l.append(x**2)
>>> l
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

How do you write it in one line? Hmm...we can...probably...use map() with lambda:

>>> list(map(lambda x: x**2, range(10)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

But isn't it clearer and simpler to just use a list comprehension?

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


Basically, we can do anything with x. Not only x**2. For example, run a method of x:

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

Or use x as another function's argument:

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

We can also, for example, use x as the key of a dict object. Let's see:

>>> d = {'foo': '10', 'bar': '20', 'baz': '30'}
>>> [d[x] for x in ['foo', 'baz']]
['10', '30']

How about a combination?

>>> d = {'foo': '10', 'bar': '20', 'baz': '30'}
>>> [int(d[x].rstrip('0')) for x in ['foo', 'baz']]
[1, 3]

And so on.


You can also use if or if...else in a list comprehension. For example, you only want odd numbers in range(10). You can do:

>>> l = []
>>> for x in range(10):
...     if x%2:
...         l.append(x)
>>> l
[1, 3, 5, 7, 9]

Ah that's too complex. What about the following version?

>>> [x for x in range(10) if x%2]
[1, 3, 5, 7, 9]

To use an if...else ternary expression, you need put the if ... else ... after x, not after range(10):

>>> [i if i%2 != 0 else None for i in range(10)]
[None, 1, None, 3, None, 5, None, 7, None, 9]


Have you heard about nested list comprehension? You can put two or more fors in one list comprehension. For example:

>>> [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]

Let's talk about the first part, for x in [[1, 2, 3], [4, 5, 6]] which gives [1, 2, 3] and [4, 5, 6]. Then, for i in x gives 1, 2, 3 and 4, 5, 6.

Warning: You always need put for x in [[1, 2, 3], [4, 5, 6]] before for i in x:

>>> [j for j in x for x in [[1, 2, 3], [4, 5, 6]]]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'x' is not defined


We also have set comprehensions, dict comprehensions, and generator expressions.

set comprehensions and list comprehensions are basically the same, but the former returns a set instead of a list:

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

It's the same as:

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

A dict comprehension looks like a set comprehension, but it uses {key: value for key, value in ...} or {i: i for i in ...} instead of {i for i in ...}.

For example:

>>> {i: i**2 for i in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

And it equals:

>>> d = {}
>>> for i in range(5):
...     d[i] = i**2
>>> d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Does (i for i in range(5)) give a tuple? No!, it's a generator expression. Which returns a generator:

>>> (i for i in range(5))
<generator object <genexpr> at 0x7f52703fbca8>

It's the same as:

>>> def gen():
...     for i in range(5):
...         yield i
>>> gen()
<generator object gen at 0x7f5270380db0>

And you can use it as a generator:

>>> gen = (i for i in range(5))
>>> next(gen)
0
>>> next(gen)
1
>>> list(gen)
[2, 3, 4]
>>> next(gen)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration

Note: If you use a list comprehension inside a function, you don't need the [] if that function could loop over a generator. For example, sum():

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

Related (about generators): Understanding Generators in Python.

这篇关于什么是“列表理解"?意思?它是如何工作的,我该如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆