我有一個元組列表。每個元組都是一個鍵值對,其中鍵是一個數字,值是一串字符。對於每個鍵我需要返回列表形式的前兩個字符和他們的計數。從元組組合中得到最高計數
例如,給定列表
[(1, "aabbc"), (1, "babdea"), (2, "aabacc"), (2, "acdad")]
鍵是1和2,值是
"aabbc", "babdea", ..., "acdaad"
元組可以轉化爲形式的元組
(1, {"a":2, "b":2, "c":1}),(1,{"a":2, "b":2, "d":1,"e":1})...(2,{"a":2, "c":1, "d":2})
對於密鑰1,
,組合元組將爲
(1,{"a":4, "b":4, "c":1, "d":1,"e":1})
使頂部兩個人物與他們的罪名是
[("a",4),("b",4)]
過程將重複每個鍵
我能得到我想要的輸出,但我正在尋找一個更好的解決方案
from collections import Counter
l=[(x[0],list(x[1])) for x in [(1, "aabbc"), (1, "babdea"), (2, "aabacc"), (2, "acdad")]]
l2=[(y[0],Counter(y[1])) for y in l]
l3=[(x[0][1],x[1][1]) for x in it.combinations(l2,2) if x[0][0]==x[1][0] ]
l4=[]
for t,y in l3:
d={}
l5=list(set(t.keys()).union(y.keys()))
for i in l5:
d[i]=t[i]+y[i]
d_sort=sorted(d.items(), key=lambda x: x[1], reverse=True)[:2]
l4.append(d_sort)
print l4
[[('a', 4), ('b', 4)], [('a', 5), ('c', 3)]]
是您的列表中關鍵字排序? – dawg