首页 > 其他 > 详细

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

时间:2017-07-17 16:50:10      阅读:355      评论:0      收藏:0      [点我收藏+]

问题

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

原文:http://www.cnblogs.com/snsdzjlz320/p/7196091.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!