首页 > 解决方案 > 计算列表元组中每个列表中给定单词的出现次数

问题描述

我有一个标记化句子的列表,我想计算几个单词的集体出现:例如:

example_list = (['hey', 'there', 'you', 'how', 'are', 'you'],
                ['i', 'am', 'fine', 'how', 'about', you],
                ['i', 'am', 'good'])

现在我想计算以下单词在每个列表中出现的次数并将分数附加到列表中

score = []
test = ['hey', 'you']

我尝试以下代码:

for i in range(len(test)):
   for j in range(len(example_list)):
       score1.append(example_list[j].count(test[i]))

并获得以下输出:

[1, 0, 0, 2, 1, 0]

而我想要一个输出:

[3, 1, 0]

有任何想法吗?

标签: pythonlistcountappend

解决方案


您可以在列表理解中使用sum :

example_list = (['hey', 'there', 'you', 'how', 'are', 'you'],
                ['i', 'am', 'fine', 'how', 'about', 'you'],
                ['i', 'am', 'good'])



test = ['hey', 'you']


score = [sum(s in test for s in lst) for lst in example_list]
print(score)

输出

[3, 1, 0]

test如果足够大,请考虑使用集合。


推荐阅读