[英]Sort a list of Python dictionaries depending on a ordered criteria
Hi, I want to order a list of dictionaries based on an ordered criteria in the most Pythonic way. 嗨,我想以一种最有Python性的方式根据有序条件对字典列表进行排序。 For example: 例如:
[{'foo': FOO1}, {'foo': FOO2}, {'foo': FOO10}]
The criteria is variable, for example, I want to order first by [FOO2, FOO1, FOO8, FOO10], the result would be: 条件是可变的,例如,我想先按[FOO2,FOO1,FOO8,FOO10]进行排序,结果将是:
[{'foo': FOO2}, {'foo': FOO1}, {'foo': FOO10}]
Then, the situation changes and now we have another criteria [FOO2, FOO10, FOO1], the result would be: 然后,情况发生变化,现在我们有了另一个标准[FOO2,FOO10,FOO1],结果将是:
[{'foo': FOO2}, {'foo': FOO10}, {'foo': FOO1}]
Note: The criteria will always have the symbols related to key 'foo'. 注意:条件将始终具有与键“ foo”相关的符号。
Any ideas? 有任何想法吗?
to_sort = [{'foo': FOO1}, {'foo': FOO2}, {'foo': FOO10}]
to_sort.sort(key=lambda x: x....)
EDIT: I figured it out: 编辑:我想通了:
>>> to_sort = [{'foo': FOO1}, {'foo': FOO2}, {'foo': FOO10}]
>>> criteria = [FOO10, FOO2, FOO1]
>>> to_sort.sort(key=lambda x: criteria.index(x['foo']))
>>> to_sort
[{'foo': FOO10}, {'foo': FOO2}, {'foo': FOO1}]
Kind regards 亲切的问候
您需要list.index()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.