Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查列表中的所有元素是否与for循环中的条件匹配的最佳方法是什么?_Python_List_For Loop - Fatal编程技术网

Python 检查列表中的所有元素是否与for循环中的条件匹配的最佳方法是什么?

Python 检查列表中的所有元素是否与for循环中的条件匹配的最佳方法是什么?,python,list,for-loop,Python,List,For Loop,我的问题和你的很相似。 但是我找不到一个正确的方法在for循环中做同样的事情。 例如,在python中使用all类似于: >>> items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] >>> all(item[2] == 0 for item in items) False 但是当我想使用类似的方法来检查for循环中的所有元素时,就像这样 >>> for item in items: >>>

我的问题和你的很相似。 但是我找不到一个正确的方法在for循环中做同样的事情。 例如,在python中使用all类似于:

>>> 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
此处不能使用“all”表达式。这里是否有类似“elif all(item[2]==0)”的可能方式。如何检查列表中的所有元素是否与for循环中的条件匹配?

此处:

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)
试试这个:-

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

您可以在
else
子句中使用
for
循环:

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

else
之后的语句是在序列的项用尽时执行的,即循环没有被
中断终止时执行的,你是指这样的情况吗

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

使用
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)

如果您想拥有
If
else
,您仍然可以使用
任何
方法:

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
来自。

这只在
False
时打印,而不是
True
时打印。经过编辑的答案,它将同时打印为什么要使用循环,如果Python有内置的用法,如
all
any
,因为我有一个For循环和一个if条件。我只想添加一个else条件来检查所有元素是否匹配一个条件。我只想知道在这个场景中是否有一种简单的方法可以使用“all”和“any”?谢谢,我只想知道在这个场景中是否有任何方法可以一次检查所有元素?谢谢,这就是我想要的!