小编apo*_*l96的帖子

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

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

example_list = (['hey', 'there', 'you', 'how', 'are', 'you'],
                ['i', 'am', 'fine', 'how', 'about', you],
                ['i', 'am', 'good'])
Run Code Online (Sandbox Code Playgroud)

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

score = []
test = ['hey', 'you']
Run Code Online (Sandbox Code Playgroud)

我尝试以下代码:

for i in range(len(test)):
   for j in range(len(example_list)):
       score1.append(example_list[j].count(test[i]))
Run Code Online (Sandbox Code Playgroud)

并获得以下输出:

[1, 0, 0, 2, 1, 0]
Run Code Online (Sandbox Code Playgroud)

而我想要输出:

[3, 1, 0]
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

python list append count

3
推荐指数
1
解决办法
158
查看次数

如果满足条件,则列表理解以更新值

我有以下列表和变量 i:

probs = [1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9]
i = 3
Run Code Online (Sandbox Code Playgroud)

我想将变量 i 中给出的索引的列表中的值更改为 3/9,并将其余值更改为 8/9。因此,上述条件的预期结果将是:

probs = [8/9, 8/9, 8/9, 3/9, 8/9, 8/9, 8/9, 8/9, 8/9]
Run Code Online (Sandbox Code Playgroud)

我更喜欢用列表理解来提高效率,有什么想法吗?

python indexing list-comprehension list

-5
推荐指数
2
解决办法
278
查看次数

标签 统计

list ×2

python ×2

append ×1

count ×1

indexing ×1

list-comprehension ×1