python - 将计数器转换为具有链接列表值的哈希表

标签 python python-3.x data-structures nltk tokenize

我有 3 个计数器,用于记录不同字符串上的词频总数。

Counter({u'childhood': 3, u'waiting': 2}) #counter1
Counter({u'childhood': 5}) #counter2
Counter({u'waiting': 2}) #counter 3

Atm 我能够执行计数器加法以获得所有计数器中所有单词的总字数。

Counter({u'childhood': 8, u'waiting': 4})

但是,我需要将每个计数器插入到哈希表中,以单词作为键,以链接列表作为值,其中每个链接条目都有每个计数器每个字符串的计数。

示例

[childhood] : [1,3] -> [2,5] #counter 1 - 3 times | counter 2 - 5 times
[waiting] : [1,3] -> [3,2]

如何在 Python 中实现这一目标?我在想一本里面有双端队列的字典?或者扩展计数器加法功能?

我尝试使用现有的 python 数据结构,而不扩展或创建自定义数据结构实现。

最佳答案

假设您有一些序列计数器

total = sum(counters, Counter())

table = {word: [counter[word] for counter in counters] for word in total}

会给你一本像

这样的字典
{
 'childhood': [3, 5, 0],
 'waiting': [2, 0, 2]
}

关于python - 将计数器转换为具有链接列表值的哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48566534/

相关文章:

c++ - 算法和数据结构

python - 创建一个非迭代器可迭代对象

algorithm - 哈希表运行时复杂度(插入、搜索和删除)

mysql - 几个单独的表格与一个带有附加列的集成表格?

python:__getattr__ 的协作 super 调用

python-3.x - 如何将字符串中的时间变量替换为纪元

python - 如何快速迭代一个大列表?

python - 确定一个字符是否不在索引处的一组括号中?

python - 为字符串列表中的子字符串实现更高效的 Python 算法

python - 为来自矩阵一列的每个线图创建图例条目