Skip to content

Instantly share code, notes, and snippets.

@aarshtalati
Created July 7, 2016 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarshtalati/a991e32e756d53e903dfe634797751da to your computer and use it in GitHub Desktop.
Save aarshtalati/a991e32e756d53e903dfe634797751da to your computer and use it in GitHub Desktop.
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