我经常遇到这样的情况:需要判断多个东西是否都等于某个值,或者至少有一个等于某个值。通常我会写类似这样的代码:
if a==1 and b==1:
do something
或者if a==1 or b==1:
do something
如果事物的数量很少,那么这样做还可以,但仍然不够优雅。那么,对于大量的事物,有更好的方法来完成上述操作吗?谢谢。如果事物的数量较少,这种方法或许可行,但不够优美。那么,针对大量事物,是否有更好的方法实现上述操作呢?谢谢。
我经常遇到这样的情况:需要判断多个东西是否都等于某个值,或者至少有一个等于某个值。通常我会写类似这样的代码:
if a==1 and b==1:
do something
或者if a==1 or b==1:
do something
如果事物的数量很少,那么这样做还可以,但仍然不够优雅。那么,对于大量的事物,有更好的方法来完成上述操作吗?谢谢。选项1:任意/全部
if all(x == 1 for x in a, b, c, d):
if any(x == 1 for x in a, b, c, d):
你也可以使用任何可迭代对象:
if any(x == 1 for x in states):
选项2 - 链式运算符和in关键字
对于您的第一个示例,您可以使用布尔运算符链式运算:
if a == b == c == d == 1:
对于你的第二个例子,你可以使用 in
:
if 1 in states:
选项3:不带谓词的任何/所有内容
如果你只关心值是否为真值,你可以进一步简化:
if any(flags):
if all(flags):
1 in [a, b, c, d]
不太好;1 in (a, b, c, d)
更好。如果下一步需要列表,请使用列表字面量。 - SingleNegationEliminationa==b==c==1
只适用于常量以及 1 in a, b, c
?它适用于任何表达式替代 1
。而 any(iterable)
/all(iterable)
不会检查所有或至少一个元素是否非零,它们检查它们是否为真。 - ZyX请看这个
if all(x >= 2 for x in (A, B, C, D)):
其中A,B,C,D都是变量...
我喜欢这个表单,因为它在Python中易于理解。
def cond(t,v):
return t == v
a=1
b=3
tests=[(a,1),(b,2)]
print any(cond(t,v) for t,v in tests) # eq to OR
print all(cond(t,v) for t,v in tests) # eq to AND
输出:
True
False
然后cond()
可以尽可能复杂。
您可以提供用户可调用项或使用operator module以获得更大的灵活性:
import operator
def condOP(t,v,op=operator.eq):
return op(t,v)
a=1
b=3
tests=[(a,1,operator.eq),(b,2,operator.gt)]
print any(condOP(*t) for t in tests) # eq to OR
print all(condOP(*t) for t in tests) # eq to AND
甚至更简单:
tests=[(a,1,operator.eq),(b,2,operator.gt)]
print any(func(t,v) for t,v,func in tests) # eq to OR
print all(func(t,v) for t,v,func in tests) # eq to AND
return t==v
或return op(t,v)
。 - dawgif cond():
而不是 if cond() == True:
,同样我也更喜欢使用 return t==v
而不是 return True if t==v else False
- 在我看来,这种写法甚至比你的 if cond(): return True return False
更符合 Python 的风格。 - ch3kaall(t == v for t, v in tests)
更简单,实际上更易读。 - Karl Knechtel
1
,对于第一个检查是不必要的,你只需要进行or
检查即可。 - wkla==1==b
。 - John La Rooy