有没有办法在python中的if语句中组合成员比较?

时间:2017-10-20 15:57:30

标签: python numpy if-statement comparison-operators multiple-conditions

  

我想检查if语句中的多个条件

if a:
    # do something

a在这种情况下适用于多种情况a == 1,a == 2,a == 3

而不是写

if a == 1 or a == 2 or a == 3:
    # do something

我正在尝试这样的事情

if a == condition for condition in [1, 2, 3]:
    # do something

4 个答案:

答案 0 :(得分:2)

你走在正确的道路上。需要的是:

if a in [1,2,3]:
   do something

替代

if a == 1 or a == 2 or a ==3:

正如 jonrsharpe 正确地指出,也许你正在尝试

if any( a==condition for condition in [1,2,3] ):

也是以同样的方式工作。

答案 1 :(得分:1)

最简单的事情是if a in (1, 2, 3)

你想写的东西可以写成

if any(a == condition for condition in [1, 2, 3])

答案 2 :(得分:1)

The truth value of an array with more than one element is ambiguous看起来像一个numpy错误消息。如果a是一个numpy ndarray并且b包含您要测试的值,则可以这样做。

import numpy as np
a = np.arange(6)
b = np.array([6,2,9])
if np.any(a == b[:, None]):
    ...

np.any(a[:,None] == b)

使用broadcasting

您的例外可以使用我的数组...

重现
>>> if a == b[:, None]:
    pass

Traceback (most recent call last):
  File "<pyshell#281>", line 1, in <module>
    if a == b[:, None]:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> 

答案 3 :(得分:1)

只是为了增加其他答案,你最好的选择肯定是这个逻辑:

if a in set([1, 2, 3]):
    #do something

甚至更好

 if a in {1, 2, 3}:
    #do something

我想在此强调的是,您应该使用set来处理这种情况。查找会更有效率。

此外,python documentation建议使用。

  

常见用途包括会员资格测试,从中删除重复项   序列,并计算数学运算,如交集,   联合,差异和对称差异