繁体   English   中英

Python:如何按值和索引对词典列表进行排序

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM