Python:在 elif 条件下循环

标签 python if-statement python-3.x

我正在运行 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 是列表而不是常量。

最佳答案

我现在明白了。执行更新编辑所说的 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()

阅读loop elses in the Python Tutorial .

关于Python:在 elif 条件下循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375661/

相关文章:

python - 导入 tensorflow 时出错 : NameError: name 'python' is not defined

python - 如何打印生成器的内容?

Python:黑色不包裹长行

python - 为什么以下 Python 中的简短脚本会忽略 "if"中的条件?

python - 从另一列 pandas df 分配值的有效方法

python - ThreadPoolExecutor().map 与 ThreadPoolExecutor().submit 有何不同?

Python Pandas - 在一个步骤中组合合并和过滤

multithreading - 如何在读取流时正确终止 Python3 线程

python - 将列表转换为字符串,但不更改任何内容

javascript - 为什么这个函数总是返回 false?