簡體   English   中英

在 python 中按連接順序對字典的值進行排序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM