參考《python cookbook》
如下例子,我們想對字典中的數據按照日期進行分組迭代峭火。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2024/8/5 下午10:14
# @Author : s
from operator import itemgetter
from itertools import groupby
rows=[{'address':'5412 N CLARK','date':'07/01/2012'},
{'address':'5148 N CLAR','date':'07/04/20121'},
{'address':'5800 E 58TH','date':'07/02/2012'},
{'address':'2122 N CLARK','date':'07/03/2012'},
{'address':'5645 N RAVENSWOOD','date':'07/02/2012'},
{'address': '1060 W ADDISON','date':'07/02/2012'},
{'address': '4801 N BROADWAY','date':'07/01/2012'},
{'address': '1039 WGRANVILLE','date':'07/04/2012'}]
# 根據日期以分組的方式迭代數據
rows.sort(key=itemgetter('date'))
print(rows)
for date, items in groupby(rows, key=itemgetter('date')):
print(date)
for i in items:
print(' ', i)
# 輸出結果:
07/01/2012
{'address': '5412 N CLARK', 'date': '07/01/2012'}
{'address': '4801 N BROADWAY', 'date': '07/01/2012'}
07/02/2012
{'address': '5800 E 58TH', 'date': '07/02/2012'}
{'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'}
{'address': '1060 W ADDISON', 'date': '07/02/2012'}
07/03/2012
{'address': '2122 N CLARK', 'date': '07/03/2012'}
07/04/2012
{'address': '1039 WGRANVILLE', 'date': '07/04/2012'}
07/04/20121
{'address': '5148 N CLAR', 'date': '07/04/20121'}