我有多个带有元组的列表,结果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
:
到目前为止,这是我的代码,但它不起作用,它无法显示索引,因为从 group by 更改索引:
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方法可以解决这个问题吗?提前致谢。
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)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句