对于循环和多个条件

2024-06-02 07:33:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在C++中,可以说:

for (int i = 0; i < 100 && !found; i++) {
  if (items[i] == "the one I'm looking for")
    found = true;
}

所以你不需要使用“break”语句。

在Python中,我想您需要编写:

found = False

for item in items:
    if item == "the one I'm looking for"
        found = True
        break

我知道我可以写一个生成器,其中有相同的代码,所以我可以隐藏这个中断的东西。但我想知道是否有其他方法可以实现相同的东西(具有相同的性能),而不使用额外的变量或while循环。

我知道我们可以说:

found = "the one I'm looking for" in items

我只是想知道在for循环中是否可以使用多个条件。

谢谢。


Tags: theinfalsetrueforifitems语句
3条回答
>>> from itertools import dropwhile
>>> try:
...     item = next(dropwhile(lambda x: x!="the one I'm looking for", items))
...     found = True
... except:
...     found = False

当然,也可以不使用lambda函数

>>> from itertools import dropwhile
>>> try:
...     item = next(dropwhile("the one I'm looking for".__ne__, items))
...     found = True
... except:
...     found = False

现在在我看来,它是使用额外变量的C版本

如果您真的只需要找到变量集(而不需要知道项),那么只需使用

found = any(item=="the one I'm looking for" for item in items)

if不是在Python中获得else子句的唯一语句:

for item in items:
  if item == "the one I'm looking for":
    break
else:
  print "Item not found! Run away! Run away!"
  return
do_something_with(item)

whiletry也有else子句。

由于Python中的^{} loops迭代的是一个序列,而不是一个条件和一个变异语句,因此break必须尽早退出。换句话说,python中的for不是条件循环。与C++的^ {< CD1> }相当的Python将是^{} loop

i=0
found=False
while i < 100 and !found:
    if items[i] == "the one I'm looking for":
        found=True
    i += 1

即使在C++中,^{} loops can be rewritten as ^{} loops如果它们不包含^ {< CD8>}语句。

{
    int i = 0;
    while (i < 100 && !found) {
        if (items[i] == "the one I'm looking for")
            found = true;
        i++;
    }
}

相关问题 更多 >