itertools.groupby函数与operator.itemgetter函数

itertools.groupby函数可以用来对数据进行分组

operator.itemgetter函数主要是用来获取对象的哪些维的数据

1. 未做排序处理

from itertools import groupby

group_list = [
    [700L,  '9.550', '2013-05-28', '600735'],
    [-1300L,  '5.390', '2013-05-27', '600701'],
    [900L,  '6.840', '2013-05-28', '600525'],
    [-900L,  '6.890', '2013-05-29', '600525'],
    [-700L,  '9.670', '2013-05-29', '600735'],
]

group_result = groupby(group_list, key=itemgetter(3))

for k, group in group_result:
    print k, list(group)

结果如下:

145321_rjjQ_2704218.png

可以看出,两个'600735'并没有被分到同一组,而两个相邻的'600525'被分到了同一组。

 

2.做了排序处理

from itertools import groupby

group_list = [
    [700L,  '9.550', '2013-05-28', '600735'],
    [-1300L,  '5.390', '2013-05-27', '600701'],
    [900L,  '6.840', '2013-05-28', '600525'],
    [-900L,  '6.890', '2013-05-29', '600525'],
    [-700L,  '9.670', '2013-05-29', '600735'],
]

group_list_sorted = sorted(group_list, key=itemgetter(3))
group_result = groupby(group_list_sorted, key=itemgetter(3))

for k, group in group_result:
    print k, list(group)

结果如下:

145648_YhHu_2704218.png

参考http://www.oschina.net/question/922781_113115,但做了修改。

 

转载于:https://my.oschina.net/wolfoxliu/blog/858351

你可能感兴趣的:(itertools.groupby函数与operator.itemgetter函数)