将计数器转换为具有链表值的哈希 Table
Convert Counters to Hash Table with Linked List values
我有 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})
然而,我需要获取每个计数器并将它们插入散列 table 中,其中单词作为键,链表作为值,其中每个链接条目都有每个计数器每个字符串的计数。
例子
[childhood] : [1,3] -> [2,5] #counter 1 - 3 times | counter 2 - 5 times
[waiting] : [1,3] -> [3,2]
如何在 Python 中实现此目的?我在想一本里面有双端队列的字典?或者扩展计数器加法功能?
我试图在不扩展或创建自定义数据结构实现的情况下使用现有的 python 数据结构。
假设你有一些序列 counters
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)]
我有 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})
然而,我需要获取每个计数器并将它们插入散列 table 中,其中单词作为键,链表作为值,其中每个链接条目都有每个计数器每个字符串的计数。
例子
[childhood] : [1,3] -> [2,5] #counter 1 - 3 times | counter 2 - 5 times
[waiting] : [1,3] -> [3,2]
如何在 Python 中实现此目的?我在想一本里面有双端队列的字典?或者扩展计数器加法功能?
我试图在不扩展或创建自定义数据结构实现的情况下使用现有的 python 数据结构。
假设你有一些序列 counters
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)]