如何迭代函数参数 [英] How to iterate over function arguments
问题描述
我有一个 Python 函数,它接受多个字符串参数 def foo(a, b, c):
并将它们连接成一个字符串.我想遍历所有函数参数以检查它们不是 None.怎么做?有没有一种快速的方法可以将 None 转换为 ""?
谢谢.
locals()
如果您在函数中首先调用它,则可能是您的朋友.
示例 1:
<预><代码>>>>定义乐趣(a,b,c):... d = 当地人()... e = d... 打印 e...打印当地人()...>>>乐趣(1, 2, 3){'a':1,'c':3,'b':2}{'a':1,'c':3,'b':2,'e':{...},'d':{...}}示例 2:
<预><代码>>>>定义无(a,b,c,d):... 参数 = locals()... 打印 '以下参数不是 None:', ', '.join(k for k, v in arguments.items() if v is not None)...>>>nones("Something", None, 'N', False)以下参数不是 None:a、c、d答案:
<预><代码>>>>def foo(a, b, c):...返回 ''.join(v for v in locals().values() 如果 v 不是 None)...>>>foo('Cleese', 'Palin', 无)'克利斯佩林'更新:
示例 1"强调,如果参数的顺序很重要,因为 locals()
(或 dict
)返回的 dict
code>vars()) 是无序的.上面的函数也没有非常优雅地处理数字.所以这里有一些改进:
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 ""?
Thanks.
locals()
may be your friend here if you call it first thing in your function.
Example 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': {...}}
Example 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
Answer:
>>> def foo(a, b, c):
... return ''.join(v for v in locals().values() if v is not None)
...
>>> foo('Cleese', 'Palin', None)
'CleesePalin'
Update:
'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屋!