2013-04-08 16 views
7

Supponiamo che io sono queste liste:Ordinamento una lista per abbinare un'altra in python

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

Come posso ordinare il objects così l'ordine dei loro ids partite ids? Cioè per ottenere questo risultato:

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

risposta

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

penso che avrei fattore dict-comp fuori in modo da non lo stai facendo più e più volte. – mgilson

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

Stranamente quasi char per char ciò che avevo nel mio editor di testi;) –

+0

@JonClements: Spendiamo chiaramente troppo tempo su questo sito;) – NPE

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

Questo non è significativamente diverso dalla risposta di NPE ... –

Problemi correlati