我有一个课程,例如:
class Row(object):
def __init__(self, res_json):
test = res_json['test']
value = res_json['value']
year = res_json['date'][0:4]
如果我有一个行对象列表,并且想按年份对它们进行分组,那么最好的方法是什么?
答案 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