有没有办法在 python 的 if 语句中结合成员比较?
Is there a way to combine memberwise comparison within an if-statement in python?
I want to check multiple conditions in an if-statement
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
最简单的写法就是if a in (1, 2, 3)
你想写的可以写成
if any(a == condition for condition in [1, 2, 3])
你走在正确的道路上。需要的是:
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] ):
这也是一样的。
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.
可以使用 my 数组重现您的异常 ...
>>> 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()
>>>
只是为了补充其他答案,你最好的选择肯定是这个逻辑:
if a in set([1, 2, 3]):
#do something
甚至更好
if a in {1, 2, 3}:
#do something
我想在这里强调的是,在这种情况下您应该使用 set
。查找会更有效率。
此外,python documentation 推荐。
Common uses include membership testing, removing duplicates from a
sequence, and computing mathematical operations such as intersection,
union, difference, and symmetric difference
I want to check multiple conditions in an if-statement
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
最简单的写法就是if a in (1, 2, 3)
你想写的可以写成
if any(a == condition for condition in [1, 2, 3])
你走在正确的道路上。需要的是:
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] ):
这也是一样的。
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.
可以使用 my 数组重现您的异常 ...
>>> 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()
>>>
只是为了补充其他答案,你最好的选择肯定是这个逻辑:
if a in set([1, 2, 3]):
#do something
甚至更好
if a in {1, 2, 3}:
#do something
我想在这里强调的是,在这种情况下您应该使用 set
。查找会更有效率。
此外,python documentation 推荐。
Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference