2016-08-03 65 views
-3

我的问题与How to check if all elements of a list matches a condition非常相似。 但我找不到在for循环中做同样事情的正确方法。 例如,使用所有在python是这样的:检查列表中的所有元素是否与for循环中的条件匹配的最佳方法?

>>> items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] 
>>> all(item[2] == 0 for item in items) 
False 

但是,当我想使用的类似的方法,以检查所有元素在for循环中这样

>>> for item in items: 
>>> if item[2] == 0: 
>>>  do sth 
>>> elif all(item[1] != 0) 
>>>  do sth 

“全”表达不能在这里使用。是否有任何可能的方法,像“elif all(item [2] == 0)”在这里使用。以及如何检查列表中的所有元素是否匹配for循环中的条件?

+0

为什么你要使用一个循环,如果Python有像'all'和'any'这样的内置用法? –

+0

因为我有一个For循环和一个if条件。我只想添加一个else条件来检查所有元素是否匹配一个条件。我只想知道在这种情况下使用'all'和'any'有没有简单的方法? –

回答

2

如果你想有一个ifelse,你仍然可以使用any方法:

if any(item[2] == 0 for item in items): 
    print('There is an item with item[2] == 0') 
else: 
    print('There is no item with item[2] == 0') 

any来自this answer

+0

谢谢,这就是我想要的! –

1

这里:

items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] 

def check_list(items): 
    for item in items: 
     if item[2] != 0: 
      return False 
    return True 

print(check_list(items)) 

如果你想成为一个更通用的:

def my_all(enumerable, condition): 
    for item in enumerable: 
     if not condition(item): 
      return False 
    return True 

print(my_all(items, lambda x: x[2]==0) 
0

试试这个: -

prinBool = True 
for item in items: 
    if item[2] != 0: 
    prinBool = False 
    break 
print prinBool 
+0

只有当'False'时才打印,如果'True'则不打印。 –

+0

是的,它只打印False –

+1

已编辑的答案,它将同时打印 –

0

你可以使用一个for循环用条款:

for item in items: 
    if item[2] != 0: 
     print False 
     break 
else: 
    print True 

else之后的语句是在序列的项目耗尽时执行的,即当循环没有被break终止时。

+0

谢谢,我只是想知道在这种情况下是否有任何方法可以一次检查所有元素? –

-1

你的意思是这样的吗?

for item in items: 
    for x in range (0,3): 
     if item[x] == 0: 
      print "True" 
0

随着functools,它会更容易:

from functools import reduce 

items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] 
f = lambda y,x : y and x[2] == 0 
reduce(f,items) 
相关问题