[英]sum of counter object of a list within a list
I am trying to find the sum of occurrence of a words from a list in a multiple lists. 我试图从多个列表中的列表中找到单词出现的总和。 the list objects within list is huge so I used just a dummy instance 列表中的列表对象很大,所以我只使用了一个虚拟实例
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]
I wanted an output like this: 我想要一个像这样的输出:
{'apple':3,'ball':2,'cat':2}
You can just feed the Counter
a generator expression: 你可以只给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
I didn't really see the point of your words
list. 我没有真正看到你的words
列表的重点。 You didn't use it. 你没有使用它。
If you need to filter out words that are not in words
, make words
a set
, not a list
. 如果您需要过滤掉不在单词中的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)
Otherwise you get O(n**2) behavior in what should be a O(n) operation. 否则,你应该在O(n)操作中获得O(n ** 2)行为。
This works in Python 2.7 and Python 3.x: 这适用于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
In Python 2.x you should use .itervalues()
instead of .values()
even though both work. 在Python 2.x中你应该使用.itervalues()
而不是.values()
即使两者都有效。
A bit shorter solution, based on roippi's answer: 根据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.