Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python : sort int list based on another int 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]
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment