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

时间:2013-04-08 13:53:08

标签: python list sorting

假设我有这些列表:

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"}
          ]

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:1)

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'}]

答案 2 :(得分:0)

>>> 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']])