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)
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)
归档时间: |
|
查看次数: |
29274 次 |
最近记录: |