使用if语句迭代列表

时间:2021-02-16 22:30:25

I have a list that I am looping through with a "for" loop and am running each value in the list through an if statement. My problem is that I am trying to only have the program do something if all the values in the list pass the if statement and if one doesn't pass, I want it to move along to the next value in the list. Currently it is returning a value if a single item in the list passes the if statement. Any ideas to get me pointed in the right direction?

我有一个列表,我循环使用“for”循环并通过if语句运行列表中的每个值。我的问题是,如果列表中的所有值都传递if语句并且如果没有传递,我试图只让程序执行某些操作,我希望它移动到列表中的下一个值。目前,如果列表中的单个项目传递if语句,则返回一个值。有什么想法让我指出正确的方向?

4 个解决方案

#1


10  

Python gives you loads of options to deal with such a situation. If you have example code we could narrow that down for you.

Python为您提供了大量选项来处理这种情况。如果您有示例代码,我们可以为您缩小范围。

One option you could look at is the all operator:

您可以看到的一个选项是all运算符:

>>> all([1,2,3,4])
True
>>> all([1,2,3,False])
False

You could also check for the length of the filtered list:

您还可以检查已过滤列表的长度:

>>> input = [1,2,3,4]
>>> tested = [i for i in input if i > 2]
>>> len(tested) == len(input)
False

If you are using a for construct you can exit the loop early if you come across negative test:

如果您使用for构造,如果遇到负面测试,可以提前退出循环:

>>> def test(input):
...     for i in input:
...         if not i > 2:
...             return False
...         do_something_with_i(i)
...     return True

The test function above will return False on the first value that's 2 or lower, for example, while it'll return True only if all values were larger than 2.

例如,上面的测试函数将在第一个值为2或更低的值时返回False,而只有在所有值都大于2时才返回True。

#2


3  

Maybe you could try with an for ... else statement.

也许你可以尝试使用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)

#3


0  

You need to loop through your whole list and check the condition before trying to do anything else with the data, so you need two loops (or use some built in that does the loop for you, like all()). From this codepad with nothing too fancy, http://codepad.org/pKfT4Gdc

在尝试对数据执行任何其他操作之前,您需要循环遍历整个列表并检查条件,因此您需要两个循环(或使用一些内置为您执行循环,如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])

#4


0  

You must always be careful if you're deleting items from your list while you're trying to iterate through it.

如果您在尝试迭代它时从列表中删除项目,则必须始终小心。

If you're not deleting then does this help:

如果您没有删除,那么这有用吗:

>>> yourlist=list("abcdefg")
>>> value_position_pairs=zip(yourlist,range(len(yourlist)))
>>> value_position_pairs
[('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6)]
>>> filterfunc=lambda x:x[0] in "adg"
>>> value_position_pairs=filter(filterfunc,value_position_pairs)
>>> value_position_pairs
[('a', 0), ('d', 3), ('g', 6)]
>>> yourlist[6]
'g'

now if value_position_pairs is empty you're done. If not you can increase i by one to go to the next value or iterate through the failed values using their position in the array.

现在,如果value_position_pairs为空,那么你已经完成了。如果不是,您可以将i增加1以转到下一个值,或使用它们在数组中的位置迭代失败的值。

#1


10  

Python gives you loads of options to deal with such a situation. If you have example code we could narrow that down for you.

Python为您提供了大量选项来处理这种情况。如果您有示例代码,我们可以为您缩小范围。

One option you could look at is the all operator:

您可以看到的一个选项是all运算符:

>>> all([1,2,3,4])
True
>>> all([1,2,3,False])
False

You could also check for the length of the filtered list:

您还可以检查已过滤列表的长度:

>>> input = [1,2,3,4]
>>> tested = [i for i in input if i > 2]
>>> len(tested) == len(input)
False

If you are using a for construct you can exit the loop early if you come across negative test:

如果您使用for构造,如果遇到负面测试,可以提前退出循环:

>>> def test(input):
...     for i in input:
...         if not i > 2:
...             return False
...         do_something_with_i(i)
...     return True

The test function above will return False on the first value that's 2 or lower, for example, while it'll return True only if all values were larger than 2.

例如,上面的测试函数将在第一个值为2或更低的值时返回False,而只有在所有值都大于2时才返回True。

#2


3  

Maybe you could try with an for ... else statement.

也许你可以尝试使用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)

#3


0  

You need to loop through your whole list and check the condition before trying to do anything else with the data, so you need two loops (or use some built in that does the loop for you, like all()). From this codepad with nothing too fancy, http://codepad.org/pKfT4Gdc

在尝试对数据执行任何其他操作之前,您需要循环遍历整个列表并检查条件,因此您需要两个循环(或使用一些内置为您执行循环,如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])

#4


0  

You must always be careful if you're deleting items from your list while you're trying to iterate through it.

如果您在尝试迭代它时从列表中删除项目,则必须始终小心。

If you're not deleting then does this help:

如果您没有删除,那么这有用吗:

>>> yourlist=list("abcdefg")
>>> value_position_pairs=zip(yourlist,range(len(yourlist)))
>>> value_position_pairs
[('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6)]
>>> filterfunc=lambda x:x[0] in "adg"
>>> value_position_pairs=filter(filterfunc,value_position_pairs)
>>> value_position_pairs
[('a', 0), ('d', 3), ('g', 6)]
>>> yourlist[6]
'g'

now if value_position_pairs is empty you're done. If not you can increase i by one to go to the next value or iterate through the failed values using their position in the array.

现在,如果value_position_pairs为空,那么你已经完成了。如果不是,您可以将i增加1以转到下一个值,或使用它们在数组中的位置迭代失败的值。