如何检查列表中的所有元素是否与条件匹配? [英] How to check if all elements of a list matches a condition?

查看:114
本文介绍了如何检查列表中的所有元素是否与条件匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像20000名单组成的名单。我使用每个列表的第三个元素作为标志。只要至少有一个元素的标志是0,我想在这个列表上做一些操作,就像:

  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,最好的选择是使用

    >>>任何(项目中的项目[2] == 0)
True


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], .....]

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(lista):
    for item in lista:
        if item[2] == 0:
            return True
    return False

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()

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:

my_list = [["a", "b"], ["c", "d"], ["e", "f"], .....]

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(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

And, for his filter example, a list comprehension:

>>> [x for x in items if x[2] == 0]
[[1, 2, 0], [1, 2, 0]]

If you want to check at least one element is 0, the better option is to use any() which is more readable:

>>> any(item[2] == 0 for item in items)
True

这篇关于如何检查列表中的所有元素是否与条件匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆