Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将计数器转换为具有链表值的哈希表_Python_Python 3.x_Data Structures_Nltk_Tokenize - Fatal编程技术网

Python 将计数器转换为具有链表值的哈希表

Python 将计数器转换为具有链表值的哈希表,python,python-3.x,data-structures,nltk,tokenize,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}) 但是,我需要将每个计数器插入到一个哈希表中,其中

我有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]
}

您可以使用
defaultdict(list)
将每个条目存储为元组:

from collections import Counter, defaultdict

counters = [
    Counter({u'childhood': 3, u'waiting': 2}), #counter1
    Counter({u'childhood': 5}),                #counter2
    Counter({u'waiting': 2})]                  #counter3    

combined = defaultdict(list)

for number, counter in enumerate(counters, start=1):
    for word, count in counter.items():
        combined[word].append((number, count))

print(combined['childhood'])
print(combined['waiting'])
这将给你:

[(1,3)、(2,5)]
[(1, 2), (3, 2)]

我认为您需要回溯一下。你怎么会有多个计数器?在生成计数器的中间列表之前,将计数放入所需的索引字典不是更容易吗?