[英]Assign dictionary values to several variables in a single line (so I don't have to run the same funcion to generate the dictionary for each one)
So I have a function that returns a dictionary.所以我有一个返回字典的 function。 The problem is that I want to assign the values of the dictionary to multiple variables, so I have to run the function several times.
问题是我想将字典的值分配给多个变量,所以我必须多次运行 function。 Is there a way to do this running the function only one time?
有没有办法只运行一次 function? Is there any elegant way to do this?
有什么优雅的方法可以做到这一点吗?
def myFunction():
a=1
b=2
c=3
d=4
df_out={"a":a, "b":b,"c":c,"d":d}
a1=myFunction()["a"]
b1=myFunction()["b"]
c1=myFunction()["c"]
d1=myFunction()["d"]
Thanks in advance!提前致谢!
def myFunction():
a=1
b=2
c=3
d=4
return {"a":a, "b":b,"c":c,"d":d}
a1, b1, c1, d1 = myFunction().values()
Assign the result to a variable, then assign each variable.将结果分配给一个变量,然后分配每个变量。
d = myFunction()
a1 = d["a"]
b1 = d["b"]
c1 = d["c"]
d1 = d["d"]
I don't think there's a one-liner for this.我不认为有一个单一的衬里。
You can use operator.itemgetter
:您可以使用
operator.itemgetter
:
from operator import itemgetter
i = itemgetter('a', 'b', 'c', 'd')
a1, b1, c1, d1 = i(myFunction())
print(a1, b1, c1, d1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.