使用itertools groupby

时间:2018-01-01 06:43:06

标签: python python-3.x itertools

我有多个列表,其中包含来自nltk.Freqdist()的元组,如下所示:

totalist[0] = [('A',12),('C',1)] #index 0
totalist[1] = [('A',25),('X',3)] #index 1
totalist[2] = [('Z',3),('T',2)] #index 2
totalist[3] = [('Z',10),('M',8)] #index 3
totalist[4] = [('Z',8),('M',8)] #index 4
totalist[5] = [('C',10),('M',8)] #index 5

我希望得到旧的索引值,即使按groupby

分组也是如此

这是我的代码到目前为止,但它无法正常工作,因为从组中改变索引而无法显示索引:

for key, group in groupby(totalist, lambda x: x[0][0]):
    for thing in group:
        #it should print it's old index value here 
    print(" ")

有没有python方法来解决这个问题?提前谢谢。

1 个答案:

答案 0 :(得分:2)

假设已经排序的列表

groupby假定列表已经排序。 示例数据满足此假设。 您可以使用enumerate保留原始索引并相应地修改键功能:

for key, group in groupby(enumerate(totalist), lambda x: x[1][0][0]):
    print(key)
    for temp_thing in group:
        old_index, thing = temp_thing
        print('    ', old_index, thing)

输出:

A
     0 [('A', 12), ('C', 1)]
     1 [('A', 25), ('X', 3)]
Z
     2 [('Z', 3), ('T', 2)]
     3 [('Z', 10), ('M', 8)]
     4 [('Z', 8), ('M', 8)]
C
     5 [('C', 10), ('M', 8)]

假设列表未排序

如果您需要先对列表进行排序,这是一个经过修改的解决方案。 最好是编写一个将用于排序和分组的函数:

def key_function(x):
    return x[1][0][0]

现在,使用此功能两次以获得一致的排序和分组:

for key, group in groupby(sorted(enumerate(totalist), key=key_function), key_function):
    print(key)
    for temp_thing in group:
        old_index, thing = temp_thing
        print('    old index:', old_index)
        print('    thing:', thing)

输出:

A
    old index: 0
    thing: [('A', 12), ('C', 1)]
    old index: 1
    thing: [('A', 25), ('X', 3)]
C
    old index: 5
    thing: [('C', 10), ('M', 8)]
Z
    old index: 2
    thing: [('Z', 3), ('T', 2)]
    old index: 3
    thing: [('Z', 10), ('M', 8)]
    old index: 4
    thing: [('Z', 8), ('M', 8)]