[英]How to sum up tuples values within a list in defaultdict using Counter?
[英]sum of counter object of a list within a list
我試圖從多個列表中的列表中找到單詞出現的總和。 列表中的列表對象很大,所以我只使用了一個虛擬實例
multiple=[['apple','ball','cat']['apple','ball']['apple','cat'].......]
words=['apple','ball','cat','duck'......]
word = 'apple'
cnt = Counter()
total = 0
for i in multiple:
for j in i:
if word in j:
cnt[word] +=1
total += cnt[word]
我想要一個像這樣的輸出:
{'apple':3,'ball':2,'cat':2}
你可以只給Counter
一個生成器表達式:
cnt = Counter(word for sublist in multiple for word in sublist)
cnt
Out[40]: Counter({'apple': 3, 'ball': 2, 'cat': 2})
sum(cnt.values())
Out[41]: 7
我沒有真正看到你的words
列表的重點。 你沒有使用它。
如果您需要過濾掉不在單詞中的words
, set
words
set
一set
, 而不是 list
。
words = {'apple','ball','cat','duck'}
cnt = Counter(word for sublist in multiple for word in sublist if word in words)
否則,你應該在O(n)操作中獲得O(n ** 2)行為。
這適用於Python 2.7和Python 3.x:
from collections import Counter
multiple=[['apple','ball','cat'],['apple','ball'],['apple','cat']]
words=['apple','ball','cat','duck']
cnt = Counter()
total = 0
for i in multiple:
for word in i:
if word in words:
cnt[word] +=1
total += 1
print cnt #: Counter({'apple': 3, 'ball': 2, 'cat': 2})
print dict(cnt) #: {'apple': 3, 'ball': 2, 'cat': 2}
print total #: 7
print sum(cnt.values()) #: 7
在Python 2.x中你應該使用.itervalues()
而不是.values()
即使兩者都有效。
根據roippi的回答,這是一個更短的解決方案:
from collections import Counter
multiple=[['apple','ball','cat'],['apple','ball'],['apple','cat']]
cnt = Counter(word for sublist in multiple for word in sublist)
print cnt #: Counter({'apple': 3, 'ball': 2, 'cat': 2})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.