简体   繁体   English

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

[英]How do I count the frequency of items for each nested list?

I have a list of lists and I would like to count the frequency of each item in each nested list.我有一个列表列表,我想计算每个嵌套列表中每个项目的频率。 I tried using Defaultdict for the counting, but I don't know how to create a nice nested list of dictionaries as output to differ between the frequencies of each list in nested_list.我尝试使用 Defaultdict 进行计数,但我不知道如何创建一个漂亮的字典嵌套列表作为输出,以在nested_list 中每个列表的频率之间有所不同。

The list:列表:

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

Desired output:期望的输出:

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

What I currently have:我目前拥有的:

dictionary = defaultdict(int)

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

Using collections.Counter , and converting to a dict :使用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}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据特定列表计算频率? - How do I count the frequency against a specific list? 如何计算列表中某项的频率? - How do to Count the frequency of an item in a list? 如何计算嵌套列表中两个项目的出现次数 - How Can I count the number of occurences for two items in a nested list numpy-如何按索引计算嵌套列表中项目的出现? - numpy - how do I count the occurrence of items in nested lists by index? 如何在列表中的句子列表中找到每个单词的引理和频率计数? - How to find the lemmas and frequency count of each word in list of sentences in a list? 如何按时间值将CSV中的数据帧分组,以便可以计算每小时的频率? - How do I group dataframe from CSV by Time Value, So that I can count frequency for each hour? 如何为多列在pyspark数据框中的一列中计算每个分类变量的频率? - How do I count frequency of each categorical variable in a column in pyspark dataframe for multiple columns? 如何将数字添加到嵌套列表中的特定项目? - How do I add numbers to specific items in a nested list? 如何为给定的外键列表中的每一个获取n项? - How do I get n items for each of the given list of foreignkey? 使用Python在嵌套列表中询问计数频率 - Asking count frequency in nested list using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM