我正在尝试返回两个词典。 person_to_friends和person_to_networks被赋予功能,profiles_file是文本文件。 我写的是:
def load_profiles(profiles_file, person_to_friends, person_to_networks):
"""
(file, dict of {str : list of strs}, dict of {str : list of strs}) -> NoneType
Update person to friends and person to networks dictionaries to include
the data in open file.
"""
profiles_file = open('data.txt', 'r')
person_to_friends = person_to_friends(profiles_file)
person_to_networks = person_to_networks(profiles_file)
return person_to_friends, person_to_networks
这只给了我person_to_friends字典..是否有人可以帮助解决这个问题? 我想要归来的是
{person_to_friends} {person_to_networks}
答案 0 :(得分:5)
简单地说:
return (person_to_friends, person_to_networks)
当你调用函数时,你需要解压返回值:
person_to_friends, person_to_networks = load_profiles(var1, var2, var3)
答案 1 :(得分:1)
您只能返回一个值(此值可以是元组,如您的情况)。但是,您可以根据需要生成尽可能多的值:
def load_profiles(profiles_file, person_to_friends, person_to_networks):
"""
(file, dict of {str : list of strs}, dict of {str : list of strs}) -> NoneType
Update person to friends and person to networks dictionaries to include
the data in open file.
"""
profiles_file = open('data.txt', 'r')
person_to_friends = person_to_friends(profiles_file)
person_to_networks = person_to_networks(profiles_file)
yield person_to_friends # you can do it without temp variable, obv.
yield person_to_networks
不同之处在于,使用yield
语句,您不能构建一个临时元组,只是一次返回两个结果。但是,从您的"功能"中获取值。 (成为发电机)会稍微困难一些:
profiles = load_profiles(your args)
实际上根本不会运行你的函数,它只是初始化一个生成器。要真正获得价值,您需要:
person_to_friends = next(profiles)
person_to_networks = next(profiles)
或只是做一个循环:
for result in load_profiles(your args):
do_something_with_your_dictionaries
因此,您的函数将返回一个值:初始化的生成器对象。在循环中迭代它(它可以是for
循环,map
,filter
,list(your_generator)
或其他东西)或只是调用next(your_generator)将为您提供这两个词典你真的需要。
答案 2 :(得分:0)
你返回两个词典的方式很好,代码的其他部分一定要搞笑,如果删除它们,一切正常:
def load_profiles():
person_to_friends = {'a' : 1}
person_to_networks = {'b' : 2}
return person_to_friends, person_to_networks
结果:
>>> load_profiles()
({'a': 1}, {'b': 2})
>>> dict_1, dict_2 = load_profiles()
>>> dict_1
{'a': 1}
>>> dict_2
{'b': 2}
答案 3 :(得分:0)
您的docstring声明函数参数person_to_friends
是
{str:list of strs}的词典
但是你把它称之为一个函数并用结果覆盖它:
person_to_friends = person_to_friends(profiles_file)
这是文档字符串或代码中的错误吗?
通过使用同名的本地定义变量(即参数),您可能正在屏蔽实际函数定义。一般来说,使用另一种截然不同的类型(例如function
)覆盖一种类型的变量(例如dict
)是不好的做法 - 尽管有例外。
答案 4 :(得分:0)
也许您可以尝试
class temp(a, b):
return dict(a=a, b=b)