繁体   English   中英

Python:在elif条件下循环

[英]Python: loop in elif condition

我正在运行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()是一些返回TrueFalse方法, n是列表的大小而不是常量。

if [ x.method() for x in list ]:

你问,有可能吗? 是。 但是它做了什么? 可能不是你想要的。

对于列表中的项目数,它将在结果列表中构造一个值。 对于列表值,只有零长度的列表将为False。 [False,False,False]为True,因此将执行条件的主体。

如果x.method()应该影响以下条件决策,您可能正在寻找all()any()

if all(x.method() for x in list):   # will require that every *x.method* call return truth.

同样,你可能想要

if any(x.method() for x in list):   # only one required. May not do every .method if it can stop early. Beware side-effects.

我不认为你想要什么 - 完全在elif - 它是可能的。 您必须评估列表中是否存在any此类值,然后将其绑定到条件中的 x 据我所知,这在Python的语法中是不可能的。 您不能在条件中进行赋值 ,并且虽然列表推导中的循环变量可以 “泄漏”到外部范围,但对于生成器来说却不是这样。

>>> if any(x for x in range(10) if x >= 5):
...     print x
NameError: name 'x' is not defined
>>> if any([x for x in range(10) if x >= 5]):
...     print x
9

在第二种情况(列表)中,我们引用了x ,但它是整个列表中的最后一个值,而在第一种情况下(生成器), x根本无法解析。


取而代之的是,这里的另一种变体,使用生成表达式组合forif ,并添加elsefor对enumate最终else条款。

if some_condition:
    print "do this"
else:
    for x in (x for x in lst if foo(x)):
        print "do this to", x
        break
    else:
        print "do something else"

我现在明白了。 做出更新编辑所说的Pythonic方法是在找到第一个项目并对其进行操作后进行for循环并突破,并使用循环中几乎未知和未使用的“其他”。

由于“for / else”习惯用法很少使用,因此您需要为将来的读者添加关于它的评论。

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教程中的循环过程

你不可能做你想做的事情,但是你可以用列表推导做类似的事情:

if some_condition:
    do this
else:
    res = [x for x in list if x.method()]
    if res:
        do something to res[0]
    else:
        do something else

为避免对每个值执行x.method() ,您还可以使用itertools.dropwhile 以下方法将继续检查x.method()直到找到一个为true,然后停止并返回x值。 如果它没有找到任何真实的东西,它将做其他事情。

from itertools import dropwhile
if some_condition:
    do this
else:
    try:
        res = next(dropwhile(lambda x: not x.method(), x))
        do something to res
    except StopIteration:
        do something else

只要您不需要在elif块之外引用x,这就可以工作。 这感觉最接近你要求的语法,但我仍然可能会使用Kevin或Tobias的答案,因为它们更明确和可读。

 def check_and_do(x):
    b = x.method()
    if b:
        do this to x
    return b

if condition:
    do this
elif any(check_and_do(x) for x in list):
    pass  # Already did this to x in check_and_do
else:
    do something else

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM