Python 计算在另一个列表中显示的数量

Python 计算在另一个列表中显示的数量,python,list,list-comprehension,Python,List,List Comprehension,我有两个列表total和word total=[['a','a','b','b','b'],['a','c']] word=['a','b'] 我想使用列表理解来输出出现在total中的每个单词的出现次数 例如: output = {'a': 2, 'b': 1} 你可以用字典来理解 {w: sum(w in l for l in total) for w in word} 你可以用字典来理解 {w: sum(w in l for l in total) for w in wo

我有两个列表
total
word

total=[['a','a','b','b','b'],['a','c']]
word=['a','b']
我想使用列表理解来输出出现在
total
中的每个单词的出现次数

例如:

output = {'a': 2, 'b': 1}      

你可以用字典来理解

{w: sum(w in l for l in total) for w in word}

你可以用字典来理解

{w: sum(w in l for l in total) for w in word}
可能是这个

from collections import Counter
from itertools import chain
total=[['a','a','b','b','b'],['a','c']]
total=[set(i) for i in total]
word=['a','b']
{k:v for k,v in Counter(chain(*total)).items() if k in word}
可能是这个

from collections import Counter
from itertools import chain
total=[['a','a','b','b','b'],['a','c']]
total=[set(i) for i in total]
word=['a','b']
{k:v for k,v in Counter(chain(*total)).items() if k in word}

如果这有效,那么你应该“接受”答案。单击问题左侧的复选标记。是的,我会的。它不允许我接受它,直到10分钟后抱歉,我已经忘记了这个限制。如果这是有效的,那么你应该“接受”答案。单击问题左侧的复选标记。是的,我会的。10分钟后我才能接受。对不起,我忘记了这个限制。注意:
chain(*total)
=>
chain.from\u iterable(total)
@Jean Françoisfare我早些时候收到过类似的评论,你介意解释一下这两个不同点吗?第一个解包到变量参数
chain
函数,第二个迭代到
total
注意:
chain(*total)
chain.from_iterable(total)
@Jean Françoisfare我早些时候收到过类似的评论,您介意解释一下这两个方面的区别吗?第一个解包到变量参数
chain
函数,第二个迭代到
total