2

我在 Python 3 中构建了以下脚本,它可以满足它的需要,但是它会遍历我的项目两次。有没有办法通过一次迭代获得相同的结果?

if any(A in B for A in C):
    for A in C:
        if A in B:
            # Do something with A.
            # Order of iteration is important.
            break
else:
    # Do something else
4

2 回答 2

1

for循环也可以有else子句,如果你不break退出它们,它们就会进入。所以你的循环可以写成

for A in C:
    if A in B:
        # Do something
        break
else:
    # Do something else
于 2018-10-05T02:28:19.213 回答
0

最有效的方法可能是在 C 级别(使用filterand next)的一次迭代中获得 A,然后立即使用它。

A = next(filter(B.__contains__, C), None)

if A is not None:
    # Do something with A
else:
    # Do something else
于 2018-10-05T18:38:30.133 回答