循环与多个条件
在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
我知道我可以写一个生成器,把相同的代码放在里面,这样就可以隐藏这个break的东西。但我想知道有没有其他方法可以实现同样的效果(性能也一样),而不需要额外的变量或while循环。
我知道我们可以这样写:
found = "the one I'm looking for" in items
我只是想了解在for循环中是否可以使用多个条件。
谢谢。
5 个回答
2
在Python中,不只有if
语句可以有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)
其实while
和try
也可以有else
部分。
3
在Python中,for
循环是用来遍历一个序列的,而不是像其他语言那样依赖条件和变化的语句。因此,如果你想提前退出循环,就需要用到break
。换句话说,Python里的for
循环并不是一个条件循环。Python中与C++的for
循环相对应的,应该是while
循环。
i=0
found=False
while i < 100 and !found:
if items[i] == "the one I'm looking for":
found=True
i += 1
即使在C++中,for
循环也可以被改写成while
循环,只要它里面没有continue
语句。
{
int i = 0;
while (i < 100 && !found) {
if (items[i] == "the one I'm looking for")
found = true;
i++;
}
}
6
>>> 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)