[英]Python: For loop over list comprehension
Is there a shorter way to write 有没有更短的书写方式
for x in [x for x in X if a(x)]:
<Do something complicated with x>
Unfortunately, the following does not work: 不幸的是,以下操作无效:
for x in X if a(x):
<Do something complicated with x>
Of course, I could achieve the desired result by 当然,我可以通过
for x in X:
if a(x):
<Do something complicated with x>
but this would introduce an extra level of indentation 但这会增加缩进程度
[b(x) for x in X if a(x)]
is the simplest but will create an unnecessary list. [b(x) for x in X if a(x)]
是最简单的,但会创建不必要的列表。
map(b, (x for x in X if a(x)))
will use a generator so no unneeded list will be created. map(b, (x for x in X if a(x)))
将使用生成器,因此不会创建不需要的列表。
Not everyone is a fan of the following, but I quite like the map and filter funcs for readability... 并非每个人都喜欢以下内容,但我非常喜欢map和filter函数以提高可读性...
list(map(b, filter(a, X))
It will achieve what you want, and I think it's easier to see what's going on. 它将实现您想要的,并且我认为更容易看到正在发生的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.