Lan*_*ins 9 python loops if-statement list
我有一个列表,我循环使用"for"循环并通过if语句运行列表中的每个值.我的问题是,如果列表中的所有值都传递if语句并且如果没有传递,我试图只让程序执行某些操作,我希望它移动到列表中的下一个值.目前,如果列表中的单个项目传递if语句,则返回一个值.有什么想法让我指出正确的方向?
Mar*_*ers 10
Python为您提供了大量选项来处理这种情况.如果您有示例代码,我们可以为您缩小范围.
您可以看到的一个选项是all运营商:
>>> all([1,2,3,4])
True
>>> all([1,2,3,False])
False
Run Code Online (Sandbox Code Playgroud)
您还可以检查已过滤列表的长度:
>>> input = [1,2,3,4]
>>> tested = [i for i in input if i > 2]
>>> len(tested) == len(input)
False
Run Code Online (Sandbox Code Playgroud)
如果你正在使用一个for构造,你可以提前退出循环,如果你遇到负面测试:
>>> def test(input):
... for i in input:
... if not i > 2:
... return False
... do_something_with_i(i)
... return True
Run Code Online (Sandbox Code Playgroud)
例如,test上面的函数将在第一个值为2或更低的值时返回False,而只有在所有值都大于2时才返回True.
也许你可以尝试用一个for ... else声明。
for item in my_list:
if not my_condition(item):
break # one item didn't complete the condition, get out of this loop
else:
# here we are if all items respect the condition
do_the_stuff(my_list)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40248 次 |
| 最近记录: |