我想知道如何按更大的元素(這里是 int 7)排序:
{'a': (2, 0, 'a'), 'b': (4, 0, 'b'), 'c': (7, 0, 'c')}
在我的整個代碼中,排序是在“一段時間”內完成的
謝謝你。
uj5u.com熱心網友回復:
sorted(d.items(), key=lambda x: x[1], reverse=True)
uj5u.com熱心網友回復:
如果我理解正確,您想按值元組中的第一項排序:
d = {'a': (2, 0, 'a'), 'b': (4, 0, 'b'), 'c': (7, 0, 'c')}
sorted_d = dict(sorted(d.items(), key=lambda x:x[1][0], reverse=True))
# {'c': (7, 0, 'c'), 'b': (4, 0, 'b'), 'a': (2, 0, 'a')}
uj5u.com熱心網友回復:
字典不能被排序,除非你覺得它不再是字典了。否則,只需一行代碼即可完成。
new_data = sorted(data.items(), key=lambda x: x[1][0], reverse=True)
data.items()包含(鍵,值)對。該key引數指示我們正在排序的內容,在本例中,它是值元組 ( x[1]) 的第零個索引。由于您希望最高值位于頂部,因此我們將reverse引數設定為True。
輸出:
[('c', (7, 0, 'c')), ('b', (4, 0, 'b')), ('a', (2, 0, 'a'))]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496871.html
上一篇:如何更改字典值中字串中的數字?
