大马强 发表于 2022-1-19 20:06:30

cookbook 1.15


根据字段将将记录分组
问题描述:
        有一系列的字典或对象实例,我们想根据某个特定的字段来分组迭代数据

一、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'}
groupby只检查连续的项,先用sorted处理很必要

二、一键多值来分组
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].append(i["name"])
for i in dt:
    print(i,dt)

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']
页: [1]
查看完整版本: cookbook 1.15