問題
你有一個字典或者例項的序列,然後你想根據某個特定的欄位(比如‘date’)來分組迭代訪問。
解決方案
itertools.groupby( )函式
itertools.groupby(rows,key=itemgetter('欄位'))
- groupby( )函式掃描整個序列並且查詢連續相同值(或者根據指定 key函式返回值相同)的元素序列
- 在呼叫groupby( )函式前,我們首先需要按照這個欄位來排序(這和SQL語句中的group by的使用是一個道理)
- 因為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'}, ] from operator import itemgetter from itertools import groupby rows.sort(key=itemgetter('date')) print(rows) [{'date': '07/01/2012', 'address': '5412 N CLARK'}, {'date': '07/01/2012', 'address': '4801 N BROADWAY'}, {'date': '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/03/2012', 'address': '2122 N CLARK'}, {'date': '07/04/2012', 'address': '5148 N CLARK'}, {'date': '07/04/2012', 'address': '1039 W GRANVILLE'}] for date,items in groupby(rows,key=itemgetter('date')): print(date) for i in items: print(' ',i) 07/01/2012 {'date': '07/01/2012', 'address': '5412 N CLARK'} {'date': '07/01/2012', 'address': '4801 N BROADWAY'} 07/02/2012 {'date': '07/02/2012', 'address': '5800 E 58TH'} {'date': '07/02/2012', 'address': '5645 N RAVENSWOOD'} {'date': '07/02/2012', 'address': '1060 W ADDISON'} 07/03/2012 {'date': '07/03/2012', 'address': '2122 N CLARK'} 07/04/2012 {'date': '07/04/2012', 'address': '5148 N CLARK'} {'date': '07/04/2012', 'address': '1039 W GRANVILLE'}