通过某个字段将记录分组
一、 解决问题
字典或者实例的序列, 想根据某个特定的字段比如 date 来分组迭代访问,类似SQL的 group by语句
二、解决方案
模块:itertools | collections
函数: groupby | defaultdict
三、代码说明
#!/user/bin/env python
# coding= utf-8
from operator import itemgetter
from itertools import groupby
rows = [
{'address': '5412 N CLARK', 'date': '07/01/2012'},
{'address': '5148 N CLARK', 'date': '07/04/2012'},
{'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 W GRANVILLE', 'date': '07/04/2012'}
]
# 需要先排序
rows.sort(key=itemgetter("date"))
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': '5148 N CLARK', 'date': '07/04/2012'}
{'address': '1039 W GRANVILLE', 'date': '07/04/2012'}
"""
# 使用多值字典
from collections import defaultdict
rows_by_date = defaultdict(list)
for row in rows:
rows_by_date[row['date']].append(row)
print (rows_by_date.keys())
四、关联知识
五、总结
六、代码地址
github地址:https://github.com/weichen666/python_cookbook
目录/文件:first_selection/leanr_itertools_groupby.py