这里是 Python 新手。
在学习 Python 的过程中,我遇到了一些非常漂亮、简洁的代码,例如:
[d[k] for k in d]
我可以立即看出这些类型的表达式有很多可能性(“这些类型”的意思包含在 [] 中)。
我不确定这种表达式叫什么,所以我在搜索有关如何使用它的信息时遇到了麻烦。对于一些知识渊博的人来说,将我引向讨论这些内容的 Python 文档或其他资源的部分,并可能提供一些有关如何有效使用它们的建议会很棒。
请您参考如下方法:
您发布的代码是一个表达式,而不是一个语句。
通常称为 list comprehension其基本结构为:
[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]
>>>
此外,还有dictionary comprehensions :
{key:value for key, value in iterable if condition}
{item for item in iterable if condition}
每个都做与列表理解相同的事情,但分别生成字典或集合。
但是请注意,您需要 Python 2.6 或更高版本才能使用这些结构。
您应该知道的最后一个工具是 generator expression :
(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
>>>
