1. 程式人生 > >[PY3]——根據某個特定的字段來分組叠代訪問一個字段或序列?/ itertools.groupby( )函數

[PY3]——根據某個特定的字段來分組叠代訪問一個字段或序列?/ itertools.groupby( )函數

問題 根據 解決 有一個 道理 style 結果 字段 lar

問題

你有一個字典或者實例的序列,然後你想根據某個特定的字段(比如‘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}

[PY3]——根據某個特定的字段來分組叠代訪問一個字段或序列?/ itertools.groupby( )函數