使用if语句遍历列表
我有一个列表,我正在用“for”循环遍历这个列表,并对每个值进行判断。我的问题是,我希望程序只有在列表中的所有值都通过判断时才执行某个操作,如果有一个值没有通过判断,我希望它就跳过这个值,继续处理下一个值。目前,如果列表中的任何一个项通过了判断,程序就会返回一个结果。有没有什么建议可以让我找到解决办法?
4 个回答
0
你需要遍历整个列表,检查条件,然后才能对数据做其他操作。所以你需要用到两个循环(或者使用一些内置的功能,比如 all(),它会帮你完成循环)。这里有一个简单的代码示例,没什么特别的,http://codepad.org/pKfT4Gdc
def my_condition(v):
return v % 2 == 0
def do_if_pass(l):
list_okay = True
for v in l:
if not my_condition(v):
list_okay = False
if list_okay:
print 'everything in list is okay, including',
for v in l:
print v,
print
else:
print 'not okay'
do_if_pass([1,2,3])
do_if_pass([2,4,6])
5
也许你可以试试用一个 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)
13
Python给你提供了很多处理这种情况的选择。如果你有示例代码,我们可以更具体地帮你分析。
你可以考虑使用all
这个操作符:
>>> all([1,2,3,4])
True
>>> all([1,2,3,False])
False
你也可以检查过滤后列表的长度:
>>> input = [1,2,3,4]
>>> tested = [i for i in input if i > 2]
>>> len(tested) == len(input)
False
如果你在使用for
循环,当遇到负面的测试时,可以提前退出循环:
>>> def test(input):
... for i in input:
... if not i > 2:
... return False
... do_something_with_i(i)
... return True
上面的test
函数会在遇到第一个值为2或更小的情况时返回False,只有当所有值都大于2时,它才会返回True。