如何迭代函数参数

jac*_*hab 29 python arguments

我有一个Python函数接受几个字符串参数def foo(a, b, c):并将它们连接在一个字符串中.我想迭代所有函数参数来检查它们不是None.怎么做?有没有快速的方法将无效转换为""?

谢谢.

Joh*_*web 36

locals() 如果你在你的职能中首先称呼它可能是你的朋友.

例1:

>>> def fun(a, b, c):
...     d = locals()
...     e = d
...     print e
...     print locals()
... 
>>> fun(1, 2, 3)
{'a': 1, 'c': 3, 'b': 2}
{'a': 1, 'c': 3, 'b': 2, 'e': {...}, 'd': {...}}
Run Code Online (Sandbox Code Playgroud)

例2:

>>> def nones(a, b, c, d):
...     arguments = locals()
...     print 'The following arguments are not None: ', ', '.join(k for k, v in arguments.items() if v is not None)
... 
>>> nones("Something", None, 'N', False)
The following arguments are not None:  a, c, d
Run Code Online (Sandbox Code Playgroud)

答案:

>>> def foo(a, b, c):
...     return ''.join(v for v in locals().values() if v is not None)
... 
>>> foo('Cleese', 'Palin', None)
'CleesePalin'
Run Code Online (Sandbox Code Playgroud)

更新:

"示例1"强调,如果参数的顺序很重要,我们可能会做一些额外的工作,因为(或)dict返回的顺序是无序的.上述功能也不能非常优雅地处理数字.所以这里有几个改进:locals()vars()

>>> def foo(a, b, c):
...     arguments = locals()
...     return ''.join(str(arguments[k]) for k in sorted(arguments.keys()) if arguments[k] is not None)
... 
>>> foo(None, 'Antioch', 3)
'Antioch3'
Run Code Online (Sandbox Code Playgroud)

  • 发现这与一个将下划线分隔的字符串转换为驼峰式字符串的函数非常有用......当从 init 参数实例化对象属性时,可以节省大量繁琐的样板代码。我还在等着让自己陷入这种编程风格的麻烦:P (2认同)

Sil*_*ost 17

def func(*args):
    ' '.join(i if i is not None else '' for i in args)
Run Code Online (Sandbox Code Playgroud)

如果你加入一个空字符串,你可以这样做 ''.join(i for i in args if i is not None)