b = [{'id': 'a'}, {'id': 'c'}, {'id': 'b'}, {'id': 'e'}]
我需要这个变成:
b = [{'id': 'a'}, {'id': 'c'}, {'id': 'e'}, {'id': 'b'}]
这个新订单由另一个列表定义。
my_filter = ['a', 'c', 'e', 'b']
...如您所见,带有字典的列表现在有一系列 ID,这些 ID 显示在 my_filter
变量上。
我可以重新排序,但使用一堆 fors 效率不高。你知道更好的方法吗?我已经知道如何sort a list of dictionaries by values of the dictionary , 但我需要这个订单由另一个列表定义。
编辑:my_filter
被命名为filter
,我在Dave Kirby's recommendation 之后更改了因为它是内置的。由于某些答案中仍然包含 filter
,因此如果您在其中一些答案中看到 filter
,此编辑部分是为了避免混淆。
最佳答案
>>> sorted(b, key=lambda x: filter.index(x['id']))
[{'id': 'a'}, {'id': 'c'}, {'id': 'e'}, {'id': 'b'}]
关于python - 使用另一个列表作为 "filter"对 python 中的字典列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6686455/