【问题标题】:How do I count the frequency of items for each nested list?如何计算每个嵌套列表的项目频率?
【发布时间】:2019-12-05 16:36:17
【问题描述】:

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

名单:

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

【问题讨论】:

    标签: python list dictionary nested frequency


    【解决方案1】:

    使用collections.Counter,并转换为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}]
    

    【讨论】:

    • 我试过这个,我得到以下错误:“ValueError:字典更新序列元素#0的长度为11;2是必需的”
    • 我给出的列表只是我正在处理的列表类型的一个基本示例。我只是不想粘贴整个列表,因为它很大。
    • 您的列表中有哪些数据类型?
    • 每个嵌套列表都包含一个字符串列表。
    • 字符串应该可以正常工作 - 我的另一个想法是您在代码中的某个地方重新定义了dict。如果你这样做print(dict),你会得到什么?
    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多