Python:返回一个dict的函数,其键是输入参数的名称 [英] Python: function that returns a dict whose keys are the names of the input arguments
问题描述
是否可以编写一个函数 f
,该函数采用混合数据的任意元组:
T = 1.0
N = 20
L = 10
args =(T,N,L)
f(* args)或者可以是f(T,N,L)?
并作为输出返回:
{'T':1.0,'N':20,'L':10}
使用<$ c $的相关问题 c> local ,但是一旦传递给该函数,我似乎丢失了名称。有办法防止这种情况吗?我猜测这些变量是通过值传递的,因此它们被认为是新的对象。
不,一般来说,这是不可能的, * args
。您必须使用关键字参数:
>>> def f(** kwargs):
pre>
... return kwargs
...
>>> f(T = 1.0,N = 20,L = 10)
{'T':1.0,'L':10,'N':20}
原因是
* args
不会为单个参数引入名称;它仅为它们的整个列表引入名称args
。该函数没有洞察参数中有什么名称(如果有的话)。
当参数数量固定时,您可以使用
本地人
:>>> def g(T,N,L):
pre
... return localals()
...
>>> g(T = 1.0,N = 20,L = 10)
{'L':10,'T':1.0,'N':20}
(或显式地使用
return {'T':T,'N':N,'L':L}
。)Is it possible to write a function
f
that takes an arbitrary tuple of mixed data:T = 1.0 N = 20 L = 10 args = (T,N,L) f(*args) # or maybe f(T,N,L)?
and returns as output:
{'T':1.0, 'N':20, 'L':10}
There is a related question using
local
, but I seem to lose the names once they are passed to the function. Is there a way to prevent this? I'm guessing that the variables are being passed by value and thus they are considered new objects.Followup: Python: Using a dummy class to pass variable names?
解决方案No, this is not possible in general with
*args
. You'll have to use keyword arguments:>>> def f(**kwargs): ... return kwargs ... >>> f(T=1.0, N=20, L=10) {'T': 1.0, 'L': 10, 'N': 20}
The reason is that
*args
does not introduce names for the individual arguments; it only introduces the nameargs
for the whole list of them. The function has no insight into how what names, if any, the arguments have outside of it.When the number of arguments is fixed, you can do this with
locals
:>>> def g(T, N, L): ... return locals() ... >>> g(T=1.0, N=20, L=10) {'L': 10, 'T': 1.0, 'N': 20}
(or explicitly with
return {'T': T, 'N': N, 'L': L}
.)这篇关于Python:返回一个dict的函数,其键是输入参数的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!