所以我遇到了一个问题,试图让我的字典在函数中更改,而不返回任何东西,下面是我的代码:
def load_twitter_dicts_from_file(filename, emoticons_to_ids, ids_to_emoticons):
in_file = open(filename, 'r')
emoticons_to_ids = {}
ids_to_emoticons = {}
for line in in_file:
data = line.split()
if len(data) > 0:
emoticon = data[0].strip('"')
id = data[2].strip('"')
if emoticon not in emoticons_to_ids:
emoticons_to_ids[emoticon] = []
if id not in ids_to_emoticons:
ids_to_emoticons[id] = []
emoticons_to_ids[emoticon].append(id)
ids_to_emoticons[id].append(emoticon)基本上,我试图做的是传入两个字典,并用文件中的信息填充它们,这工作得很好,但在我调用它并尝试打印这两个字典后,它显示它们是空的。有什么想法吗?
发布于 2015-11-20 04:47:00
def load_twitter_dicts_from_file(filename, emoticons_to_ids, ids_to_emoticons):
…
emoticons_to_ids = {}
ids_to_emoticons ={}这两行代码将替换您传递给函数的任何内容。因此,如果您将两个字典传递给该函数,则这些字典永远不会被触动。相反,您需要创建两个从未传递给外部的新字典。
如果要修改传递给函数的字典,请删除这两行并首先创建字典。
或者,您也可以在函数末尾返回这两个字典:
return emoticons_to_ids, ids_to_emoticonshttps://stackoverflow.com/questions/33814008
复制相似问题