python - 如何计算每个嵌套列表的项目频率?
问题描述
我有一个列表列表,我想计算每个嵌套列表中每个项目的频率。我尝试使用 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
解决方案
使用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}]
推荐阅读
- javascript - 刷新后将项目添加到本地存储时,我会丢失其他项目
- javascript - Select2js 将通过 ajax 调用获得的结果与用户输入分开
- jquery - jQuery,一个接一个地启动一堆异步调用
- typo3 - TYPO3 10.4 - 找不到区域设置“en_US.UTF-8”
- splunk - Splunk 索引和空间使用
- python - 熊猫 - 处理 NaN
- python - 使用混合语法设置多个主键
- java - Java 安装错误:“停止!`java 13.0.2-open` 已安装”
- android - 如何将代码从改造更改为凌空
- sql - 将光标添加到此查询后,执行时间从 10s 变为 2m.10s