在python中排序一个列表以匹配另一个列表

1cklez4t  于 2023-02-21  发布在  Python
关注(0)|答案(4)|浏览(149)

假设我有这些列表:

ids = [4, 3, 7, 8]
objects = [
             {"id": 7, "text": "are"},
             {"id": 3, "text": "how"},
             {"id": 8, "text": "you"},
             {"id": 4, "text": "hello"}
          ]

如何对objects进行排序,使其id的顺序与ids匹配?例如,要获得以下结果:

objects = [
             {"id": 4, "text": "hello"},
             {"id": 3, "text": "how"},
             {"id": 7, "text": "are"},
             {"id": 8, "text": "you"}
          ]
kuuvgm7e

kuuvgm7e1#

object_map = {o['id']: o for o in objects}
objects = [object_map[id] for id in ids]
6yt4nkrj

6yt4nkrj2#

In [25]: idmap = dict((id,pos) for pos,id in enumerate(ids))

In [26]: sorted(objects, key=lambda x:idmap[x['id']])
Out[26]: 
[{'id': 4, 'text': 'hello'},
 {'id': 3, 'text': 'how'},
 {'id': 7, 'text': 'are'},
 {'id': 8, 'text': 'you'}]
z8dt9xmd

z8dt9xmd3#

>>> ids = [4,3,7,8]
>>> id_orders = {}
>>> for i,id in enumerate(ids):
...     id_orders[id] = i
... 
>>> id_orders
{8: 3, 3: 1, 4: 0, 7: 2}
>>> 
>>> sorted(objs, key=lambda x: id_orders[x['id']])
bbmckpt7

bbmckpt74#

sorted与自定义key函数一起使用,该函数只是从ids获取index

sorted(objects, key=lambda x: ids.index(x['id']))

(灵感来自NPE’s answer。)

相关问题