【问题标题】:Python return with multiple dictionaries from a functionPython从一个函数返回多个字典
【发布时间】:2017-11-23 02:03:28
【问题描述】:

我的问题是我有两个函数,其中一个函数的返回值是两个字典,方式如下:

def fnct1():
    return dict1, dict2

所以它返回到我的另一个函数,返回值是前一个函数的两个字典和一个新字典,所以像这样

 def fnct2():
     return dict3, fnct(1)

问题在于,结果如下:

({dict3},({dict1},{dict2})

但我希望它看起来像下面这样:

({dict3},{dict1},{dict2})

【问题讨论】:

  • 你能展示你想出的代码吗?另外,the help centre 有一些关于代码正确格式的信息。
  • 格式不好,我以后会更加小心

标签: python dictionary return


【解决方案1】:

由于您的函数返回一个元组,您需要返回单个元组项,或者将它们解包:

def fnct1():
    dict1 = { "name": "d1" }
    dict2 = { "name": "d2" }
    return dict1, dict2

def fnct2():
    dict3 = { "name": "d3" }
    res = fnct1() 
    return dict3, res[0], res[1] # return the individual tuple elements

# alternative implementation of fnct2:
def fnct2():
    dict3 = { "name": "d3" }
    d1, d2 = fnct1() # unpack your tuple
    return dict3, d1, d2

print(fnct2())
# Output: ({'name': 'd3'}, {'name': 'd1'}, {'name': 'd2'})

【讨论】:

  • 感谢我一直在寻找的答案,或者有没有办法将 dict3 添加到元组中,而不是解压这两个已经存在的东西?
  • @Klftau 元组是不可变的,因此您无法更改它们,但是您可以将元组添加在一起(在新元组中)以模仿这种行为。试试return (dict3,) + fnct1()。
【解决方案2】:

您可以在返回之前从fnct1() 解压这些值:

def fnct2():
    dict1, dict2 = fnct1()
    return dict3, dict1, dict2

【讨论】:

    【解决方案3】:

    如果你说第一个函数的返回值是a。在第二个只是return a[0], a[1], otherDict。

    【讨论】:

      猜你喜欢
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多