如何检查列表中的所有元素是否都符合条件? [英] How to check if all elements of a list match a condition?
问题描述
我有一个包含20000个列表的列表.我将每个列表的第3个元素用作标志.只要至少一个元素的标志为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:
my_list = [["a", "b", 0], ["c", "d", 0], ["e", "f", 0], .....]
开头,所有标志均为0.我使用while循环检查至少一个元素的标志是否为0:
In the beginning, all flags are 0. I use a while loop to check if at least one element's flag is 0:
def check(list_):
for item in list_:
if item[2] == 0:
return True
return False
如果 check(my_list)
返回 True
,则我将继续处理列表:
If 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上进行迭代时删除其中的一个元素,但是当我对其进行迭代时,不允许删除项目.
Actually, I wanted to remove an element in my_list as I iterated over it, but I'm not allowed to remove items as I iterate over it.
原始my_list没有标志:
Original my_list didn't have flags:
my_list = [["a", "b"], ["c", "d"], ["e", "f"], .....]
由于在迭代过程中无法删除元素,因此发明了这些标志.但是 my_list
包含许多项,而 while
循环会在每个 for
循环中读取所有这些项,这会花费大量时间!你有什么建议吗?
Since I couldn't remove elements as I iterated over it, I invented these flags. But the 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?
推荐答案
最好的答案是使用生成器表达式结合使用,以产生干净而有效的结果.例如:
The best answer here is to use 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(flag == 0 for (_, _, flag) in items)
True
>>> items = [[1, 2, 0], [1, 2, 1], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
False
请注意, all(项目中的(_,_,flag)的标志== 0)
直接等效于 all(项目中的项目的item [2] == 0)
,在这种情况下,阅读起来会更好一些.
Note that all(flag == 0 for (_, _, flag) in items)
is directly equivalent to all(item[2] == 0 for item in items)
, it's just a little nicer to read in this case.
对于过滤器示例,使用列表理解(当然,您可以在适当的地方使用生成器表达式):
And, for the filter example, a list comprehension (of course, you could use a generator expression where appropriate):
>>> [x for x in items if x[2] == 0]
[[1, 2, 0], [1, 2, 0]]
如果要检查至少一个元素为0,则更好的选择是使用 any()
更具可读性:
If you want to check at least one element is 0, the better option is to use any()
which is more readable:
>>> any(flag == 0 for (_, _, flag) in items)
True
这篇关于如何检查列表中的所有元素是否都符合条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!