|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
根据字段将将记录分组
问题描述:
有一系列的字典或对象实例,我们想根据某个特定的字段来分组迭代数据
一、groupby分组from operator import itemgetter
datas = [{"name": "小白 m 18", "date": "07/04/2021"},
{"name": "小黄 m 18", "date": "24/01/2021"},
{"name": "小橙 m 19", "date": "01/05/2021"},
{"name": "小蓝 w 18", "date": "23/04/2021"},
{"name": "小紫 m 19", "date": "01/05/2021"},
{"name": "小绿 m 18", "date": "01/07/2021"}]
datas.sort(key=itemgetter("date"))
for date, item in groupby(datas, key=itemgetter("date")):
print(date)
for i in item:
print(" ", i)
01/05/2021
{'name': '小橙 m 19', 'date': '01/05/2021'}
{'name': '小紫 m 19', 'date': '01/05/2021'}
01/07/2021
{'name': '小绿 m 18', 'date': '01/07/2021'}
07/04/2021
{'name': '小白 m 18', 'date': '07/04/2021'}
23/04/2021
{'name': '小蓝 w 18', 'date': '23/04/2021'}
24/01/2021
{'name': '小黄 m 18', 'date': '24/01/2021'}
[b]groupby只检查连续的项,先用sorted处理很必要[/b]
二、一键多值来分组from collections import defaultdict
datas = [{"name": "小白 m 18", "date": "07/04/2021"},
{"name": "小黄 m 18", "date": "24/01/2021"},
{"name": "小橙 m 19", "date": "01/05/2021"},
{"name": "小蓝 w 18", "date": "23/04/2021"},
{"name": "小紫 m 19", "date": "01/05/2021"},
{"name": "小绿 m 18", "date": "01/07/2021"}]
dt = defaultdict(list)
for i in datas:
# dt.setdefault(i["date"]).append(i["name"])
dt[i["date"]].append(i["name"])
for i in dt:
print(i, dt[i])
07/04/2021 ['小白 m 18']
24/01/2021 ['小黄 m 18']
01/05/2021 ['小橙 m 19', '小紫 m 19']
23/04/2021 ['小蓝 w 18']
01/07/2021 ['小绿 m 18']
|
|