当使用operator.itemgetter填充时,itertools.groupby返回空列表项

时间:2014-01-22 17:04:52

标签: python operator-keyword itertools

我正在尝试使用函数groupby和itemgetter来重新排列元组的排序列表

from itertools import groupby
from operator import itemgetter

#initialize a list of tuples
indexed_qualityresults = [(u'moses-R4', 2.0), (u'moses-R4', 3.0), (u'lucy-R4', 3.0), (u'trados-R4', 2.0)]

#group tuples, using as a key the first element of each tuple
groupped_qualityresults = list(groupby(indexed_qualityresults, itemgetter(0)))

#print the key and the respective grouped tuples for each group
print "groupped_qualityresults =", [(a,list(b)) for a,b in groupped_qualityresults]

输出

groupped_qualityresults = [(u'moses-R4', []), (u'lucy-R4', []), (u'trados-R4', [(u'trados-R4', 2.0)])]

如您所见,然后为tmy原始元组列表的两个第一个键返回的列表是空的,尽管它们不应该是。

预期产出:

groupped_qualityresults = [(u'moses-R4', [(u'moses-R4', 2.0), (u'moses-R4', 3.0)]), (u'lucy-R4', [(u'lucy-R4', 3.0)]), (u'trados-R4', [(u'trados-R4', 2.0)])]

有人可以识别出错的地方吗?

1 个答案:

答案 0 :(得分:5)

不要在list()迭代器上调用groupby

#group tuples, using as a key the first element of each tuple
groupped_qualityresults = groupby(indexed_qualityresults, itemgetter(0))

#print the key and the respective grouped tuples for each group
print "groupped_qualityresults =", [(a,list(b)) for a,b in groupped_qualityresults]

来自itertools.groupby() documentation

  

返回的组本身就是一个迭代器,它与groupby()共享底层的iterable。由于源是共享的,因此当groupby()对象前进时,前一个组将不再可见。

groupby()的输出转换为列表会使groupby()对象前进。