Python,按任意顺序对一系列的字典进行排序[复制](Python, sort a list of dicts by an arbitrary order [duplicate])

编程入门 行业动态 更新时间:2024-10-25 18:23:25
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}]

Possible Duplicate: Sorting list of lists by a third list of specified non-sorted order

a = [{'id':1}, {'id':2}, {'id':3}] b = [2,1,3]

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.

更多推荐

本文发布于:2023-07-28 01:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298308.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   顺序   系列   sort   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!