【发布时间】:2015-04-01 07:55:46
【问题描述】:
我正在运行 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 是列表的大小而不是常量。
【问题讨论】:
-
您能否提供一个具体示例来说明您正在尝试做什么?
list的内容是什么?some_condition是什么?do this是什么?x.method()是什么?do this to x是什么?do something else是什么?您希望看到的具体输出是什么? -
@Kevin 我添加了对概念的另一个澄清,我猜可能是迄今为止最清晰的。
标签: python if-statement python-3.x