测试值是否存在于多个列表中 [英] Test if value exists in several lists
本文介绍了测试值是否存在于多个列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查每个列表中是否都存在一个值.
I would like to check if a value exists in every list.
以下内容按预期返回True
,但似乎不符合Python规范.
The following returns True
as expected, but seems un-pythonic.
什么是正确/更优雅的方式?
What is the correct/more elegant way to do this?
a = [1 ,2]
b = [1, 3]
c = [1, 4]
d = [2, 5]
False in [True if 1 in l else False for l in [a, b, c, d] ]
推荐答案
all(1 in x for x in (a, b, c, d))
演示:
>>> a = [1 ,2]
>>> b = [1, 3]
>>> c = [1, 4]
>>> d = [2, 5]
>>> all(1 in x for x in (a, b, c, d))
False
>>> all(1 in x for x in (a, b, c))
True
>>>
除了更具可读性之外,此解决方案还更有效,因为它使用了惰性求值.它只会检查确定结果所需的尽可能多的项目.
In addition to being more readable, this solution is more efficient since it uses lazy-evaluation. It will only check as many items as is necessary to determine the result.
此外,从来没有充分的理由这样做:
Also, there is never a good reason to do:
True if 1 in l else False
或类似的东西,因为in
已经返回了布尔结果.您只需要:
or something similar since in
already returns a boolean result. All you need is:
1 in l
对于否定版本,请使用:
For the negated version, use:
1 not in l
这篇关于测试值是否存在于多个列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文