我有一个字典列表,其中字典本身也有一个列表。如何使用因子索引进行排序?
例如,按以下顺序对列表进行排序 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]}]
本质上,您需要做的是使用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'}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句