按字典列表索引对字典列表进行排序

时间:2020-06-11 16:19:19

标签: python list python-2.7 dictionary

我有一个字典列表,其中字典本身也有一个列表。如何使用因子索引进行排序?

例如,按factors[0]

对列表进行降序排序
[{'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]}, {'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]}, {'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]}, {'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]}]

2 个答案:

答案 0 :(得分:1)

您可以将其作为密钥传递

my_list=[{'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]}, {'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]}, {'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]}, {'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]}]
sorted(my_list, key=lambda x: x['factors'][0])

输出:

[{'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]},
 {'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]},
 {'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]},
 {'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]}]

答案 1 :(得分:1)

基本上,您需要做的是使用sorted。但是,这个factors[0]似乎有些武断,也许您想先对列表进行排序,然后再按其第一个值进行排序?

然而,这个例子可以完成工作。请记住,它不适用于联系,因此您可能要添加第二个排序键:

sort = sorted(ex, key=lambda x: x['factors'][0])
sort

输出:

[{'factors': [1.25, 2.25, 2.5, 2.0, 1.75], 'id': 756, 'score': '1.9'},
 {'factors': [1.5, 3.0, 1.5, 2.5, 1.5], 'id': 863, 'score': '1.9'}, #Tied values
 {'factors': [1.5, 3.0, 2.5, 1.5, 1.5], 'id': 55, 'score': '2.0'}, #Tied values
 {'factors': [2.0, 2.25, 2.75, 1.5, 2.25], 'id': 686, 'score': '2.0'}]

对于绑定值,按factors[0]后跟id排序的示例。请注意顺序是相反的,首先按ID排序(内部排序),然后按代码因素排序(外部排序):

sort = sorted(sorted(ex,key=lambda x: x['id']),key=lambda x: x['factors'][0])
sort

输出:

[{'factors': [1.25, 2.25, 2.5, 2.0, 1.75], 'id': 756, 'score': '1.9'},
 {'factors': [1.5, 3.0, 2.5, 1.5, 1.5], 'id': 55, 'score': '2.0'},
 {'factors': [1.5, 3.0, 1.5, 2.5, 1.5], 'id': 863, 'score': '1.9'},
 {'factors': [2.0, 2.25, 2.75, 1.5, 2.25], 'id': 686, 'score': '2.0'}]