Python:存储与字典中的键关联的列表值
我知道 python 字典如何存储键:值元组。在我正在进行的项目中,我需要存储与列表值关联的键。 前任: 键-> [0,2,4,5,8] 在哪里, key 是文本文件中的一个单词 列表值包含代表该单词出现的 DocID 的整数。
一旦我在另一个文档中找到相同的单词,我就需要将该 DocID 附加到列表中。
我怎样才能实现这个目标?
I know how python dictionaries store key: value tuples. In the project I'm working on, I'm required to store key associated with a value that's a list.
ex:
key -> [0,2,4,5,8]
where,
key is a word from text file
the list value contains ints that stand for the DocIDs in which the word occurs.
as soon as I find the same word in another doc, i need to append that DocID to the list.
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用 defaultdict,如下所示:
You can use defauldict, like this:
这将是使用
defaultdict
如果必须的话,你可以使用列表而不是集合
This would be a good place to use
defaultdict
you can use a list instead of a set if you have to
这篇文章对我解决了在动态创建带有附加数据列表的变量键时遇到的问题很有帮助。见下文:
它输出每个键的数据列表,然后可以更改为 np.array 用于绘图等。
This post was helpful for me to solve a problem I had in dynamically creating variable keys with lists of data attached. See below:
Which outputs the data lists for each key and then can be changed to a np.array for plotting etc.
像这样的东西吗?
Something like this?
我曾经编写过一个帮助器类来制作 @Vinko Vrsalovic`s 答案更容易使用:
可以这样使用:
I once wrote a helper class to make @Vinko Vrsalovic`s answer easier to use:
This can be used like this:
如果我答对了你的问题,你可以试试这个,
这适用于旧版本的 python
If i get your question right,You can try this ,
This will work with older versions of python