![](/img/trans.png)
[英]How to call an index value from an itertools permutation without converting it to a list?
[英]Get index value from categorized List with itertools groupby
我有多個由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(" ")
有什么辦法解決這個問題嗎? 提前致謝。
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)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.