博客
关于我
Python 字典键映射多个值,字典值为列表,defaultdict
阅读量:256 次
发布时间:2019-03-01

本文共 689 字,大约阅读时间需要 2 分钟。

背景

在处理大量数据时,涉及到元组或列表的记录归纳统计时,需要将所有列表转换为字典以便统计。以下是一个示例:

l1 = ['张三', '语文', 50]l2 = ['李四', '语文', 60]l3 = ['张三', '数学', 70]l4 = ['李四', '数学', 60]

期望结果为:

{    '张三': [50, 70],    '李四': [60, 60]}

代码

from collections import defaultdictl1 = ['张三', '语文', 50]l2 = ['李四', '语文', 60]l3 = ['张三', '数学', 70]l4 = ['李四', '数学', 60]result = defaultdict(list)for record in (l1, l2, l3, l4):    name = record[0]    score = record[2]    result[name].append(score)print(result)

分析

defaultdict的作用是,当字典中的键不存在时,返回默认值而不是KeyErrordefaultdict接受一个工厂函数作为参数,用于在键不存在时创建默认值。例如:

  • defaultdict(list):当键不存在时,返回一个空列表。
  • defaultdict(set):当键不存在时,返回一个空集合。
  • defaultdict(str):当键不存在时,返回一个空字符串。

优点

  • 不再需要检查字典键是否存在。
  • 代码简洁,易于维护。
  • 适合批量处理数据。

参考文章

你可能感兴趣的文章
pilicat-dfs 霹雳猫-分布式文件系统
查看>>
Pillow lacks the JPEG 2000 plugin
查看>>
SpringBoot之ElasticsearchRestTemplate常用示例
查看>>
ping 全网段CMD命令
查看>>
ping 命令的七种用法,看完瞬间成大神
查看>>
Pinia入门(快速上手)
查看>>
Pinia:$patch的使用场景
查看>>
Pinia:$subscribe()的使用场景
查看>>
Pinpoint对Kubernetes关键业务模块进行全链路监控
查看>>
Pinterest 大规模缓存集群的架构剖析
查看>>
pintos project (2) Project 1 Thread -Mission 1 Code
查看>>
PinYin4j库的使用
查看>>
PIP
查看>>
pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
查看>>
pip install mysqlclient报错
查看>>
pip install 出现报asciii码错误的解决
查看>>
pip throws TypeError: parse() got an unexpected keyword argument ‘transport_encoding‘ 在尝试安装新软件包时
查看>>
pip 下载慢
查看>>
pip 升级报错AttributeError: ‘NoneType’ object has no attribute ‘bytes’
查看>>
pip 安装opencv-python卡死
查看>>