如何循环函数参数 [英] How to iterate over function arguments
问题描述
我有一个Python函数接受几个字符串参数 DEF美孚(A,B,C):
和字符串串联它们。
我想遍历所有的函数参数来检查他们不无。如何可以做到?
是否有一个快速的方法来转换成无为?
I have a Python function accepting several string arguments def foo(a, b, c):
and concatenating them in a string.
I want to iterate over all function arguments to check they are not None. How it can be done?
Is there a quick way to convert None to ""?
感谢。
推荐答案
当地人()
可能是你的朋友在这里,如果你把它的第一件事就是你的函数。
locals()
may be your friend here if you call it first thing in your function.
示例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': {...}}
例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
答
>>> def foo(a, b, c):
... return ''.join(v for v in locals().values() if v is not None)
...
>>> foo('Cleese', 'Palin', None)
'CleesePalin'
更新
'例1'的亮点,我们可能有一些额外的工作要做,如果你的参数的顺序是作为字典
按返回当地人重要()
(或瓦尔()
)是无序的。以上且功能不带数字处理非常优雅。因此,这里有一对夫妇改进的:
'Example 1' highlights that we may have some extra work to do if the order of your arguments is important as the dict
returned by locals()
(or vars()
) is unordered. The function above also doesn't deal with numbers very gracefully. So here are a couple of refinements:
>>> 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'
这篇关于如何循环函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!