如何计算每个嵌套列表的项目频率?

2024-04-19 23:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表列表,我想计算每个嵌套列表中每个项目的频率。我尝试使用Defaultdict进行计数,但是我不知道如何创建一个很好的嵌套字典列表作为输出,以区别嵌套列表中每个列表的频率。你知道吗

列表:

nested_list = [[hello, hello, hello, how, are, you],[1, 2, 2, 2],[tree, flower, tree]]

期望输出:

final_list = [{hello: 3, how: 1, are: 1, you: 1}, {1: 1, 2: 3}, {tree: 2, flower:1}]

我目前拥有:

dictionary = defaultdict(int)

for item in nested_list: 
    for x in item:
        dictionary[x] += 1

Tags: 项目inyoutreehello列表fordictionary
1条回答
网友
1楼 · 发布于 2024-04-19 23:29:50

使用^{},并转换为dict

>>> from collections import Counter
>>> [dict(Counter(x)) for x in nested_list]
[{'hello': 3, 'how': 1, 'are': 1, 'you': 1},
 {1: 1, 2: 3},
 {'tree': 2, 'flower': 1}]

相关问题 更多 >