简体   繁体   中英

Pythonic way for checking equality in AND condition

I have a piece of code which looks like below:

a = None
b = None
c = None
d = None

if a==None and b==None and c==None and d==None:
    print("All are None")
else:
    print("Someone is not None")

What would be the pythonic way or shorter way to achieve this as I have more number of variables to check like this?

You can use a list, and check all items in the list using list comprehension:

l_list = [None, None, None, None, None]
if all(item is None for item in l_list):
    print("All items are None")

You can chain the comparisons:

if a is b is c is d is None:
    print("All are None")
else:
    print("Someone is not None")

if not all((a, b, c, d)):

or

if not any((a, b, c, d)): if you want to check if any of the item is not None

Does this help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM