测试所有值是否以pythonic方式迭代

时间:2022-05-10 22:23:19

I am currently doing this:

我目前正在这样做:

if x in a and y in a and z in a and q in a and r in a and s in a:
    print b

Is there a more pythonic way to express this if statement?

是否有更多的pythonic方式来表达这个if语句?

4 个解决方案

#1


29  

Using the all function allows to write this in a nice and compact way:

使用all函数可以以一种漂亮而紧凑的方式编写它:

if all(i in a for i in (x, y, z, q, r, s)):
    print b

This code should do almost exactly the same as your example, even if the objects are not hashable or if the a object has some funny __contains__ method. The all function also has similar short-circuit behavior as the chain of and in the original problem. Collecting all objects to be tested in a tuple (or a list) will guarantee the same order of execution of the tests as in the original problem. If you use a set, the order might be random.

此代码应该与您的示例几乎完全相同,即使对象不可散列或者对象具有一些有趣的__contains__方法。 all函数也具有与原始问题链中相似的短路行为。在元组(或列表)中收集要测试的所有对象将保证与原始问题中的测试执行顺序相同。如果您使用集合,则订单可能是随机的。

#2


18  

Another way to do this is to use subsets:

另一种方法是使用子集:

if {x, y, z, q, r, s}.issubset(a):
    print(b)

REPL example:

>>> {0, 1, 2}.issubset([0, 1, 2, 3])
True
>>> {0, 1, 2}.issubset([1, 2, 3])
False

One caveat with this approach is that all of x, y, z, etc. must be hashable.

这种方法的一个警告是x,y,z等都必须是可清洗的。

#3


7  

if all(v in a for v in {x, y, z, q, r, s}):
    print(b)

#4


3  

Converting to set, either:

转换为set,或者:

if len({x, y, z, q, r, s} - set(a)) == 0:
    print b

or

t = {x, y, z, q, r, s}
if t & set(a) == t:
    print b

#1


29  

Using the all function allows to write this in a nice and compact way:

使用all函数可以以一种漂亮而紧凑的方式编写它:

if all(i in a for i in (x, y, z, q, r, s)):
    print b

This code should do almost exactly the same as your example, even if the objects are not hashable or if the a object has some funny __contains__ method. The all function also has similar short-circuit behavior as the chain of and in the original problem. Collecting all objects to be tested in a tuple (or a list) will guarantee the same order of execution of the tests as in the original problem. If you use a set, the order might be random.

此代码应该与您的示例几乎完全相同,即使对象不可散列或者对象具有一些有趣的__contains__方法。 all函数也具有与原始问题链中相似的短路行为。在元组(或列表)中收集要测试的所有对象将保证与原始问题中的测试执行顺序相同。如果您使用集合,则订单可能是随机的。

#2


18  

Another way to do this is to use subsets:

另一种方法是使用子集:

if {x, y, z, q, r, s}.issubset(a):
    print(b)

REPL example:

>>> {0, 1, 2}.issubset([0, 1, 2, 3])
True
>>> {0, 1, 2}.issubset([1, 2, 3])
False

One caveat with this approach is that all of x, y, z, etc. must be hashable.

这种方法的一个警告是x,y,z等都必须是可清洗的。

#3


7  

if all(v in a for v in {x, y, z, q, r, s}):
    print(b)

#4


3  

Converting to set, either:

转换为set,或者:

if len({x, y, z, q, r, s} - set(a)) == 0:
    print b

or

t = {x, y, z, q, r, s}
if t & set(a) == t:
    print b