我试图找到多个列表中列表中单词的出现次数之和。list中的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
中的单词,则使words
为set
, 不为list
。
words = {'apple','ball','cat','duck'}
cnt = Counter(word for sublist in multiple for word in sublist if word in words)
否则你会得到O(n**2)个行为,而本应是O(n)个操作
这适用于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中。你应该使用.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})