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

时间:2018-08-09 22:54:32

标签: python sorting

我有一个数据字典的列表,该字典在某些地方是有序的,而在其他地方是无序的:

例如:

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'])

我还如何添加字典的索引?

还有我可以使用的更好的排序键吗?

3 个答案:

答案 0 :(得分:3)

您似乎正在寻找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)现在处于另一顺序;希望我能正确阅读您的想法。


根据操作说明更新

我检查了文档。 Python的sort方法是 stable ,因此您根本不需要第二个排序键:如果出现平局,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}]

...这就是您所要求的。

答案 1 :(得分:2)

使用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}]
>>> 

答案 2 :(得分:-1)

您尝试过吗:

$ echo "$#: $@"
: 
$ set A=B c d
$ echo "$#: $@"
3: A=B c d