立即检查一组变量的布尔值

NIl*_*rma 4 python boolean

我有大约10个布尔变量,x=True如果所有这十个变量值都是True ,我需要设置一个新的布尔变量.如果其中一个是False然后设置x= False我可以这样做

if (a and b and c and d and e and f...):
    x = True
else:
    x=False
Run Code Online (Sandbox Code Playgroud)

这显然看起来非常难看.请建议更多的pythonic解决方案.

丑陋的部分是 a and b and c and d and e and f...

jam*_*lak 9

假设你在列表/元组中有bool:

x = all(list_of_bools)
Run Code Online (Sandbox Code Playgroud)

或者正如@minopret所建议的那样

x= all((a, b, c, d, e, f))
Run Code Online (Sandbox Code Playgroud)

例:

>>> list_of_bools = [True, True, True, False]
>>> all(list_of_bools)
False
>>> list_of_bools = [True, True, True, True]
>>> all(list_of_bools)
True
Run Code Online (Sandbox Code Playgroud)

  • 对,你可以直接写一个列表或元组:`all((a,b,c,d,e,f))` (5认同)