Python 用于循环过滤列表

Python 用于循环过滤列表,python,Python,我有密码 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 comma

我有密码

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

它确实管用,但你知道,它很难看有更聪明的方法吗?

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

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

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

您也可以使用while循环执行此操作:

list=iter(list_origin)
element=next(list,None) if list_origin[0].some_boolean_property() else None
while(element.some_boolean_property()):
    # several complicated commands here,
    element=next(list,None) 
你可以使用列表,但它并不比你的列表更难看。现在发电机是首选的方式

for item in filter(lambda x: x.some_boolean_property(), list):
    several complicated commands here

为什么不事先过滤列表,这样就可以直接使用for循环而不需要if条件呢?只需使用if item.some\u boolean\u属性,而不需要使用continue@BelhadjerSamir你看过问题了吗?这就是OP所做的。他们想救一个孩子indent@BelhadjerSamir,重点是删除一级缩进,但如果item.some_boolean_属性:是否完全相反,如问题中所示是的,我知道了,向上投票