If I have a construct like this:
如果我有这样一个构念:
def foo():
a=None
b=None
c=None
#...loop over a config file or command line options...
if a is not None and b is not None and c is not None:
doSomething(a,b,c)
else:
print "A config parameter is missing..."
What is the preferred syntax in python to check if all variables are set to useful values? Is it as I have written, or another better way?
python中检查所有变量是否设置为有用值的首选语法是什么?是像我写的那样,还是另一种更好的方式?
This is different from this question: not None test in Python ... I am looking for the preferred method for checking if many conditions are not None. The option I have typed seems very long and non-pythonic.
这与这个问题不同:在Python中不是没有测试…我正在寻找的首选方法,以检查是否有许多条件不是没有。我输入的选项看起来很长而且不是python语言的。
2 个解决方案
#1
23
There's nothing wrong with the way you're doing it.
你这样做没有错。
If you have a lot of variables, you could put them in a list and use all
:
如果你有很多变量,你可以把它们放在一个列表中,然后使用所有的变量:
if all(v is not None for v in [A, B, C, D, E]):
#2
2
Complementing Daniel Roseman's answer, I think:
补充Daniel Roseman的回答,我认为:
if all([a,b,c,d]):
is cleaner
更清洁
Since all()
built-in function already iterates over the list checking for None
values
因为all()内置函数已经遍历列表,检查无值
#1
23
There's nothing wrong with the way you're doing it.
你这样做没有错。
If you have a lot of variables, you could put them in a list and use all
:
如果你有很多变量,你可以把它们放在一个列表中,然后使用所有的变量:
if all(v is not None for v in [A, B, C, D, E]):
#2
2
Complementing Daniel Roseman's answer, I think:
补充Daniel Roseman的回答,我认为:
if all([a,b,c,d]):
is cleaner
更清洁
Since all()
built-in function already iterates over the list checking for None
values
因为all()内置函数已经遍历列表,检查无值