循环过滤列表

我有代码

for item in list:
    if item.some_boolean_property():
        several complicated commands here

我想将这些for和压缩if成一个表达式,以便命令可以少缩进一级。我能够将其重构为代码

for item in [item for item in list if item.some_boolean_property()]:
    several complicated commands here

它确实有效,但是,你知道,它很丑陋。:) 有没有更聪明的方法来做到这一点?

回答

要保存一个缩进级别,请使用continue跳过您不感兴趣的迭代:

for item in list:
    if not item.some_boolean_property():
        continue # skip this iteration

    # several complicated commands here,
    # one indentation level less than above!

  • @BelhadjerSamir did you read the question? That is what OP does. They want to save an indent

以上是循环过滤列表的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>