Ban*_*ach 0 python for-loop list-comprehension
是否有更短的写作方式
for x in [x for x in X if a(x)]:
<Do something complicated with x>
Run Code Online (Sandbox Code Playgroud)
不幸的是,以下不起作用:
for x in X if a(x):
<Do something complicated with x>
Run Code Online (Sandbox Code Playgroud)
当然,我可以达到预期的效果
for x in X:
if a(x):
<Do something complicated with x>
Run Code Online (Sandbox Code Playgroud)
但这会引入额外的缩进程度
[b(x) for x in X if a(x)] 是最简单的,但会创建一个不必要的列表.
map(b, (x for x in X if a(x))) 将使用生成器,因此不会创建不需要的列表.
不是每个人都喜欢以下内容,但我非常喜欢地图和过滤器功能以提高可读性......
list(map(b, filter(a, X))
Run Code Online (Sandbox Code Playgroud)
它会实现你想要的,而且我认为更容易看到发生了什么。