我正在运行 Python 3。
是否可以在elif
的条件中放置一个循环?这是我想要实现的基本想法。列表中的项目数量不是恒定的。
if some_condition:
do this
elif [ x.method() for x in list ]:
do this to x
else:
do something else
现在,我想到了这一点:
if some_condition:
do this
for x in list:
if x.method():
do this to x
break
但是我试图避免运行所有的 if 语句,其中发生了很多事情。我想专门将其放在 elif
部分中,而不是放在 else
中。
编辑/更多说明:
看来我需要的是 any( x.method() for x in list )
但也需要引用 x
以便我可以使用 x
如果条件为真。
这是我试图再次了解的整个概念:
if condition:
do this
elif list[0].method():
do this to list[0]
elif list[1].method():
do this to list[1]
...
elif list[n].method():
do this to list[n]
else:
do this
其中 method()
是返回 True
或 False
的方法,n
是列表而不是常量。
最佳答案
我现在明白了。执行更新编辑所说的 Pythonic 方法是创建一个 for 循环,并在找到第一个项目并对其执行操作后中断,并使用循环中几乎未知且未使用的“else”。
由于“for/else”习语很少使用,因此您需要为 future 的读者添加有关它的注释。
if some_test:
first_action()
else:
for item in list:
if item.method():
do_this(item)
break # process no more of list
else: # for-else only entered if no break from the list!
final_action()
关于Python:在 elif 条件下循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375661/