像[d[k] for k in d]这样的表达式叫什么?

1 投票
1 回答
3658 浏览
提问于 2025-04-29 08:04

我是一名Python新手。

在学习Python的过程中,我遇到了一些非常简洁的代码,比如:

[d[k] for k in d]

我立刻能看出来,这种表达式有很多种可能性(“这种”是指那些包含在[]里的)。

我不太确定这种表达式叫做什么,所以在搜索相关信息时遇到了困难。如果有懂行的人能指引我去Python文档的相关部分,或者其他资源,讨论一下这些内容,那就太好了,也希望能给我一些有效使用它们的建议。

暂无标签

1 个回答

8

你发的代码是一个表达式,而不是一个语句。

它通常被称为列表推导式,基本结构是:

[item for item in iterable if condition]

其中的if condition部分是可选的。结果是一个新的列表对象,它是从iterable中的项目创建的(可能会通过if condition进行过滤):

>>> [x for x in (1, 2, 3)]  # Get all items in the tuple (1, 2, 3).
[1, 2, 3]
>>> [x for x in (1, 2, 3) if x % 2]  # Only get the items where x % 2 is True.
[1, 3]
>>>

另外,还有字典推导式

{key:value for key, value in iterable if condition}

以及集合推导式

{item for item in iterable if condition}

它们的功能和列表推导式相同,但分别生成字典或集合。

不过要注意,你需要使用Python 2.6或更高版本才能使用这些结构。


最后一个你应该了解的工具是生成器表达式

(item for item in iterable if condition)

它和列表推导式类似,创建一个生成器对象,这个对象会懒惰地生成它的项目(根据需要一个一个地生成):

>>> (x for x in (1, 2, 3))
<generator object <genexpr> at 0x02811A80>
>>> gen = (x for x in (1, 2, 3))
>>> next(gen)  # Advance the generator 1 position.
1
>>> next(gen)  # Advance the generator 1 position.
2
>>> next(gen)  # Advance the generator 1 position.
3
>>> next(gen)  # StopIteration is raised when there are no more items.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

撰写回答