Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算列表元组中每个列表中给定单词的出现次数_Python_List_Count_Append - Fatal编程技术网

Python 计算列表元组中每个列表中给定单词的出现次数

Python 计算列表元组中每个列表中给定单词的出现次数,python,list,count,append,Python,List,Count,Append,我有一个标记化句子的列表,我想计算几个单词的集体出现次数: e、 g: 现在我想计算以下单词在每个列表中出现的次数,并将分数附加到一个列表中 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

我有一个标记化句子的列表,我想计算几个单词的集体出现次数: e、 g:

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

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]
鉴于我希望输出:

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

有什么想法吗?

只需使用传统的
循环:

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

for lst in example_list:
    total = 0
    for word in test:
        total += lst.count(word)
    score.append(total)

print(score)
输出:

[3, 1, 0]

您可以将嵌套列表理解与
sum
一起使用,以添加
test
中所有元素的出现次数

此外,您可能希望从
测试
中构建
,以便更快地查找:

test = set(['hey', 'you'])

[sum(s in test for s in l) for l in example_list]
# [3, 1, 0]
您可以在列表中使用:

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]

如果
测试
足够大,请考虑使用一个集合。

您可以使用
计数器
执行此任务:

from collections import Counter


counters = [Counter(l) for l in example_list]
occurrences = [sum([c[word] for word in test if word in c]) for c in counters]

print(occurrences) # [3, 1, 0]

您是否也有一个智能的方法来计算每个列表的嵌套长度?i、 e该列表中有多少个单词?@apol96
[len(lst)表示示例列表中的lst]