[英]Python: How to sort list of dictionaries by value and index
我有一個數據字典的列表,該數據字典在某些地方是有序的,而在其他地方是無序的:
例如:
data = [{"text":'a', "value":1},
{"text":'b', "value":1},
{"text":'j', "value":2},
{"text":'k', "value":50},
{"text":'b', "value":50},
{"text":'y', "value":52},
{"text":'x', "value":2},
{"text":'k', "value":3},
{"text":'m', "value":3}]
我想將它們排序為:
o = [{"text":'a', "value":1},
{"text":'b', "value":1},
{"text":'j', "value":2},
{"text":'x', "value":2},
{"text":'k', "value":3},
{"text":'m', "value":3},
{"text":'k', "value":50},
{"text":'b', "value":50},
{"text":'y', "value":52}]
其中我的排序是項目索引和第二個值的某種組合,我當時在考慮排序:
key=[(2nd value)<<len(closest power of 2 to len(index)) + index]
我可以用第二個值按字典列表排序:
data.sort(key= lambda x:x['value'])
如何添加字典的索引?
還有我可以使用的更好的排序鍵嗎?
看來您正在尋找text
字段作為輔助排序鍵。 最簡單的方法是簡單地按優先級使用元組作為鍵:
sorted(data, key=lambda x: (x['value'], x['text']) )
滿足您的需求嗎? 輸出:
[{'text': 'a', 'value': 1}, {'text': 'b', 'value': 1}, {'text': 'j', 'value': 2}, {'text': 'x', 'value': 2}, {'text': 'k', 'value': 3}, {'text': 'm', 'value': 3}, {'text': 'b', 'value': 50}, {'text': 'k', 'value': 50}, {'text': 'y', 'value': 52}]
值(k,50)和(b,50)現在處於其他順序; 希望我能正確閱讀您的想法。
每個OP的更新說明
我檢查了文檔。 Python的sort
方法是穩定的 ,因此您根本不需要第二個sort鍵:萬一出現平局, sort
將保持原始順序:
>>> data.sort(key= lambda x:x['value'])
>>> data
[{'text': 'a', 'value': 1}, {'text': 'b', 'value': 1}, {'text': 'j', 'value': 2}, {'text': 'x', 'value': 2}, {'text': 'k', 'value': 3}, {'text': 'm', 'value': 3}, {'text': 'k', 'value': 50}, {'text': 'b', 'value': 50}, {'text': 'y', 'value': 52}]
...這就是您的要求。
使用enumerate
獲取索引並使用該索引進行排序
>>> res = [d for i,d in sorted(enumerate(data), key=lambda i_d: (i_d[1]['value'], i_d[0]))]
>>> pprint(res)
[{'text': 'a', 'value': 1},
{'text': 'b', 'value': 1},
{'text': 'j', 'value': 2},
{'text': 'x', 'value': 2},
{'text': 'k', 'value': 3},
{'text': 'm', 'value': 3},
{'text': 'k', 'value': 50},
{'text': 'b', 'value': 50},
{'text': 'y', 'value': 52}]
要對其進行原位排序,可以嘗試使用itertools.count
>>> from itertools import count
>>> cnt=count()
>>> data.sort(key=lambda d: (d['value'], next(cnt)))
>>> pprint(data)
[{'text': 'a', 'value': 1},
{'text': 'b', 'value': 1},
{'text': 'j', 'value': 2},
{'text': 'x', 'value': 2},
{'text': 'k', 'value': 3},
{'text': 'm', 'value': 3},
{'text': 'k', 'value': 50},
{'text': 'b', 'value': 50},
{'text': 'y', 'value': 52}]
>>>
您是否嘗試過:
sorted(data, key=lambda x: x['value'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.