如何检查列表中的所有元素是否与条件匹配?

2024-04-24 15:06:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单,大约有两万份。我使用每个列表的第三个元素作为标志。我想在此列表上执行一些操作,只要至少有一个元素的标志为0,如下所示:

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

开始时,所有标志都是0。我使用while循环检查是否至少有一个元素的标志为0:

def check(list_):
    for item in list_:
        if item[2] == 0:
            return True
    return False

如果check(my_list)返回True,则继续处理列表:

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包含许多项,并且while循环在每个for循环读取所有项,并且它消耗大量时间!你有什么建议吗?


Tags: infalsetrue元素列表forreturnif
3条回答

如果要检查列表中的任何项是否违反条件,请使用all

if all([x[2] == 0 for x in lista]):
    # Will run if all elements in the list has x[2] = 0 (use not to invert if necessary)

要删除所有不匹配的元素,请使用filter

# Will remove all elements where x[2] is 0
listb = filter(lambda x: x[2] != 0, listb)

您可以使用itertools的takewhile like this,it will stop once a condition is met that fails your statement。相反的方法是dropwhile

for x in itertools.takewhile(lambda x: x[2] == 0, list)
    print x

这里最好的答案是使用^{},这是这种情况下的内置选项。我们将其与generator expression结合,以产生您想要的干净高效的结果。例如:

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

如果要检查至少一个元素是0,则更好的选择是使用更可读的^{}

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

相关问题 更多 >