Python新手在这里.
在学习Python时,我遇到了一些非常好的,简洁的代码,例如:
[d[k] for k in d]
Run Code Online (Sandbox Code Playgroud)
我可以立即看到这些表达式有很多可能性("这些类型"含义包含在a中[]).
我不能确定什么这种表达是叫,所以我无法寻找关于如何使用它的信息.对于一些知识渊博的人来说,指导我学习Python文档或讨论这些文档的其他资源,或者提供一些如何有效使用它们的建议会很棒.
您发布的代码是表达式,而不是语句.
它通常被称为列表理解,其基本结构是:
[item for item in iterable if condition]
Run Code Online (Sandbox Code Playgroud)
该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]
>>>
Run Code Online (Sandbox Code Playgroud)
另外,还有字典理解:
{key:value for key, value in iterable if condition}
Run Code Online (Sandbox Code Playgroud)
并设置理解:
{item for item in iterable if condition}
Run Code Online (Sandbox Code Playgroud)
每个都与列表理解相同,但分别产生字典或集合.
但请注意,您需要Python 2.6或更高版本才能使用这些构造.
您应该知道的最后一个工具是生成器表达式:
(item for item in iterable if condition)
Run Code Online (Sandbox Code Playgroud)
与列表推导类似,它创建了一个生成器对象,它懒洋洋地生成它的项目(一次需要一个):
>>> (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
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1354 次 |
| 最近记录: |