我知道 python 字典如何存储键:值元组。在我正在处理的项目中,我需要存储与列表值关联的键。 前任: 键 -> [0,2,4,5,8] 在哪里, key 是来自文本文件的单词 列表值包含代表单词出现的 DocID 的整数。
只要我在另一个文档中找到相同的词,我就需要将该 DocID 附加到列表中。
我怎样才能做到这一点?
请您参考如下方法:
您可以像这样使用 defauldict:
>>> import collections
>>> d = collections.defaultdict(list)
>>> d['foo'].append(9)
>>> d
defaultdict(<type 'list'>, {'foo': [9]})
>>> d['foo'].append(90)
>>> d
defaultdict(<type 'list'>, {'foo': [9, 90]})
>>> d['bar'].append(5)
>>> d
defaultdict(<type 'list'>, {'foo': [9, 90], 'bar': [5]})
