如何在python中按年份对行对象列表进行分组?

时间:2019-04-01 14:17:36

标签: python python-3.x oop

我有一个课程,例如:

class Row(object):
    def __init__(self, res_json):
        test = res_json['test']
        value = res_json['value']
        year = res_json['date'][0:4]

如果我有一个行对象列表,并且想按年份对它们进行分组,那么最好的方法是什么?

1 个答案:

答案 0 :(得分:2)

使用itertools.groupby

from itertools import groupby
from operator import attrgetter

rows = []  # list of row objects

for year, group in groupby(rows, key=attrgetter('year')):
    # do stuff with the year and the group here