python sort a list of objects based on attributes in the order of the other list

list, python, sorting

Solution

>>> from collections import namedtuple
>>> Foo = namedtuple('Foo', 'name id') # this represents your class with id attribute
>>> a = [1,2,3,4,5]
>>> b = [Foo(name='o', id=2), Foo(name='p', id=1), Foo(name='q', id=3), Foo(name='r', id=5), Foo(name='s', id=4)]
>>> sorted(b, key=lambda x: a.index(x.id))
[Foo(name='p', id=1), Foo(name='o', id=2), Foo(name='q', id=3), Foo(name='s', id=4), Foo(name='r', id=5)]

Problem

I am working with Python list sort. I have two lists: one is a list of integers, the other is a list of objects, and the second object list has the attribute id which is also an integer, I want to sort the object list based on the id attribute, in the order of the same id appears in the first list, well, this is an example: I got `a = [1,2,3,4,5]` and `b = [o,p,q,r,s]`, where o.id = 2, p.id = 1, q.id = 3, r.id = 5, s.id = 4 and I want my list b to be sorted in the order of its id appears in list a, which is like this: `sorted_b = [p, o, q, s, r]` Of course, I can achieve this by using nested loops: ``` sorted_b = [] for i in a: for j in b: if j.id == i: sorted_b.append(j) break ``` but this is a classic ugly and non-Python way to solve a problem, I wonder if there is a way to solve this in a rather neat way, like using the sort method, but I don't know how.

Original source