[英]in python sort the values of a dictionary in order of connection
我試圖找到解決方案。 也許我的話選錯了。 對不起我的英語不好。
我有一本字典。
d= {'A': [tg, 17], 'B': [59, 60], 'C': [60, 61], 'D': [57, tt], 'E': [61, tg], 'F': [tt, 59]}
sorted_keys = sorted(d, key=lambda k: (d[k], k), reverse=True)`
預期的結果是: [17,tg,61,60,59,tt,57]
提前謝謝
有人幫我找到了答案。 我分享給你這個。
d = {'A': ['tg', 17], 'B': [59, 60], 'C': [60, 61], 'D': [57, 'tt'], 'E': [61, 'tg'], 'F': ['tt', 59]}
# we build a inverted dictonnary to return the list
# the tuple of values [v1, v2] for each value v{1,2}
# { 17: [['tg', 17]],
# 57: [[57, 'tt']],
# 'tg': [['tg', 17], [61, 'tg']],
# 60: [[59, 60], [60, 61]], ... }
dico = dict()
for i in d.values():
for j in i:
dico[j] = dico.get(j, []) + [i]
# we get a piece of the list, that easy there is one instance
m = min(l := [j for i in d.values() for j in i], key=l.count) # py 3.8
z = [m]
v1, v2 = dico[m][0]
v = v1 if v2 == m else v2 # we get the other value of the tuple
z.append(v)
while len(dico[v]) > 1: # until we a not a the end of the chain
v1, v2 = [i for i in dico[v] if m not in i][0]
m = v
v = v1 if v2 == m else v2
z.append(v)
print(z)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.