我有一个方法/函数,它传递了几个可能具有None值的变量。如何检查None值的所有变量并用尽可能最pythonic方式的字符串替换它?
示例代码:
def logData(self, var1=None, var2=None, var3=None):
if var1 is None:
var1 = "---"
if var2 is None:
var2 = "---"
if var3 is None:
var3 = "---"
# what I would prefer / pseudo code:
if list(var1, var2, var3) is None:
list[1] = "---"
答案 0 :(得分:2)
使用元组解包:
var1, var2, var3 = ['---' if (x is None) else x for x in (var1, var2, var3)]
答案 1 :(得分:2)
var1, var2, var3 = (a or '---' for a in [var1, var2, var3])
答案 2 :(得分:-1)
您可以使用**kwargs
:
def logData(self, **kwargs):
for key,value in kwargs.iteritems():
if value is None:
# do assignment ...