如何检查列表中的所有元素是否与条件匹配? [英] How to check if all elements of a list matches a condition?
问题描述
my_list = [ [a,b,0],[c,d,0],[e,f,0],.....]
在开始时,所有的标志都是0.我使用while循环来检查至少一个元素的标志是否为0:
def check(lista):
for lista中的项目:
if item [2] == 0:
返回True
返回False
如果 check(my_list)
返回 True
,然后我继续处理我的列表:
check my_list:
for my_list:
如果条件:
item [2] = 1
else:
do_sth()
实际上我想在my_list中移除元素,但是我不能删除项目,我迭代它。
原始的my_list没有标志:
my_list = [[a,b],[c,d],[ e,f],.....]
因为我无法删除当我重复它时,我发明了这些标志。但是 my_list
包含很多项目,而循环在
/ code>循环,并且会消耗大量时间!你有什么建议吗?
这里最好的答案是使用 all()
,这是内置的这种情况。我们将其与生成器表达式结合使用,以产生您想要的清晰高效的结果。例如:
>>> items = [[1,2,0],[1,2,0],[1,2,0]]
>>>所有(项目中的item [2] == 0)
True
>>> items = [[1,2,0],[1,2,1],[1,2,0]]
>>>所有(项目中的item [2] == 0项目)
False
为他的过滤器的例子,一个列表解析:
>>> [x for x in items if x [2] == 0]
[[1,2,0],[1,2,0]]
如果你想检查至少一个元素是0,最好的选择是使用 I have a list consisting of like 20000 lists. I use each list's 3rd element as a flag. I want to do some operations on this list as long as at least one element's flag is 0, it's like: In the beginning all flags are 0. I use a while loop to check if at least one element's flag is 0: If Actually I wanted to remove element in my_list as I iterated over it, but I'm not allowed to remove item as I iterate over it. Original my_list didn't have flags: Since I couldn't remove elements as I iterated over it, I invented these flags. But the The best answer here is to use And, for his filter example, a list comprehension: If you want to check at least one element is 0, the better option is to use
这篇关于如何检查列表中的所有元素是否与条件匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
>>>任何(项目中的项目[2] == 0)
True
my_list = [["a", "b", 0], ["c", "d", 0], ["e", "f", 0], .....]
def check(lista):
for item in lista:
if item[2] == 0:
return True
return False
check(my_list)
returns True
, then I continue working on my list:while check(my_list):
for item in my_list:
if condition:
item[2] = 1
else:
do_sth()
my_list = [["a", "b"], ["c", "d"], ["e", "f"], .....]
my_list
contains many items, and while
loop reads all of them at each for
loop, and it consumes lots of time! Do you have any suggestions?all()
, which is the builtin for this situation. We combine this with a generator expression to produce the result you want cleanly and efficiently. For example:>>> items = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
>>> all(item[2] == 0 for item in items)
True
>>> items = [[1, 2, 0], [1, 2, 1], [1, 2, 0]]
>>> all(item[2] == 0 for item in items)
False
>>> [x for x in items if x[2] == 0]
[[1, 2, 0], [1, 2, 0]]
any()
which is more readable:>>> any(item[2] == 0 for item in items)
True