简体   繁体   English

将字典值分配给一行中的多个变量(因此我不必运行相同的函数来为每个变量生成字典)

[英]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.

相关问题 使用 DictWriter 在每一行中写入一个字典的值 - Write values of a dictionary one in each line with DictWriter 在 Python 中,我将如何比较一个字典中的两个值在另一个字典中具有相同的值? - In Python how would I compare 2 values in one dictionary that have the same values in another dictionary? 如何创建一个字典,从列表中分配值并为每个值生成相同的键 - How to create a dictionary assigning values from a list and generate the same key for each one 如果我在列表中有值但没有键,如何创建字典? - How create a dictionary if I have its values in a list but I don't have its keys? Python-将多个字典值关联到一行中的不同变量 - Python - Assigining multiple dictionary values to different variables in one line 将几个对象的值合并到一个字典中 - combine values of several objects into a single dictionary 使用相同的键将变量分配给字典项 - Assign variables to dictionary items with same key 将返回字典中的值分配给唯一变量 - Assign values in returned dictionary to unique variables 有没有一种方法可以为同一行中的多个变量分配数字? - Is there a way to assign numbers to several variables in the same line? 如何将字典分配给 Python 中的每个另一个字典的值? - How to assign a dictionary to each of another dictionary's values in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM