Python : sort int list based on another


This post discusses how to custom sort one list in python based on the order of elements of another list.

>>> a=[2, 3, 4, 5, 6, 7, 8]
>>> b=[4, 2, 3, 8, 1, 5, 7, 6]
>>> sorted(a, key = lambda x: b.index(x))
[4, 2, 3, 8, 5, 7, 6]
>>> a=[2, 3, 4, 5, 6, 7, 8, 9]
>>> sorted(a, key = lambda x: b.index(x))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
ValueError: 9 is not in list
# better way : test 1
>>> sorted(a, key = lambda x: b.index(x) if x in b else len(a))
[4, 2, 3, 8, 5, 7, 6, 9]
# better way : test 2
>>> a=[2, 3, 4, 5, 6, 7, 8, 9, 45]
>>> sorted(a, key = lambda x: b.index(x) if x in b else len(a))
[4, 2, 3, 8, 5, 7, 6, 9, 45]
# better way : test 3
>>> a=[2, 3, 4, 5, 6, 108, 7, 8, 9, 45, 1]
>>> sorted(a, key = lambda x: b.index(x) if x in b else len(a))
[4, 2, 3, 8, 5, 7, 6, 108, 9, 45, 1]
>>>

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s