1. 判断多个变量全部/任意不为空

我们在写Python 函数的时候,可能会需要判断传入的多个参数是否同时为空/None/False,或者是否有任何一个不为空/None/False。可能有人会这样写:

# 判断三个函数不能同时为空
def func1(name_list, id_list, is_first):
    if not name_list and not id_list and not is_first:
        print('三个参数不能同时为空!')
 
 
# 判断三个参数必需全都不为空
def func2(name_list, id_list, is_first):
    if name_list and id_list and is_first:
        print('三个参数全都不为空')

2. 简单写法 any/all

这样写虽然可以达到效果,但是要多写几个and或者or总是有点麻烦。

实际上,在Python里面有两个内置的关键字all和any可以快速实现这个目的。

all关键字接受一个列表,这个列表里面的多个元素必需同时不为None False 空列表/空字符串/空元组/空…… 数字0它才会返回True.

例如:

>>> all(['hello', 'world', []])
False
>>> all(['hello', 'world', True])
True
>>> all(['hello', 'world', 12])
True
>>> all([])
True

而any的作用刚刚相反。它也是接受一个列表,列表里面只要有一个元素不为None False 空列表/空字符串/空元组/空…… 数字0就会返回True。

>>> any(['', 0, False, []])
False
>>> any(['', 1, False, []])
True
>>> any(['hello', 0, False, []])
True

所以,原来的func1和func2可以做一下修改,变得更加简洁:

# 判断三个函数不能同时为空
def func1(name_list, id_list, is_first):
    if any([name_list, id_list, is_first]):
        print('三个参数里面,至少有一个不为空')
 
 
# 判断三个参数必需全都不为空
def func2(name_list, id_list, is_first):
    if all([name_list, id_list, is_first]):
        print('三个参数同时不为空')