首页 > 代码库 > [PY3]——根据某个特定的字段来分组迭代访问一个字段或序列?/ itertools.groupby( )函数

[PY3]——根据某个特定的字段来分组迭代访问一个字段或序列?/ itertools.groupby( )函数

问题

你有一个字典或者实例的序列,然后你想根据某个特定的字段(比如‘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 itemgetterfrom itertools import groupbyrows.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( )函数