Python,按任意顺序对一系列的字典进行排序[复制](Python, sort a list of dicts by an arbitrary order [duplicate])
a = [{'id':1}, {'id':2}, {'id':3}] b = [2,1,3]可能重复: 按指定的非排序顺序的第三个列表对列表进行排序
通过id属性按list b对dict a进行排序的好方法是什么。
结果应该看起来像这样
[{'id':2}, {'id':1}, {'id':3}]a = [{'id':1}, {'id':2}, {'id':3}] b = [2,1,3]Possible Duplicate: Sorting list of lists by a third list of specified non-sorted order
What would be a good method to sort dict a by list b via the id property.
The result should look something like this
[{'id':2}, {'id':1}, {'id':3}]最满意答案
不需要巫术,只要你可以保证b已经填入了所有的id :
In [1]: a = [{'id':1}, {'id':2}, {'id':3}] In [2]: b = [2,1,3] In [3]: a.sort(key=lambda v : b.index(v['id'])) In [4]: a Out[4]: [{'id': 2}, {'id': 1}, {'id': 3}](我经常被告知现在应该使用lambda的替代方法,但这仍然是我知道的最清晰的方式)
编辑:另请注意,这与链接问题中的此答案几乎完全相同。
No voodoo is required, as long as you can guarantee b has been populated with all the ids in a:
In [1]: a = [{'id':1}, {'id':2}, {'id':3}] In [2]: b = [2,1,3] In [3]: a.sort(key=lambda v : b.index(v['id'])) In [4]: a Out[4]: [{'id': 2}, {'id': 1}, {'id': 3}](I'm often told there's an alternative to lambda that should be used nowadays, but this is still the clearest way I know for doing this)
EDIT: Also note that this is nearly identical to this answer in the linked question.
更多推荐
发布评论