Created
July 7, 2016 12:55
-
-
Save aarshtalati/a991e32e756d53e903dfe634797751da to your computer and use it in GitHub Desktop.
Python : sort int list based on another int list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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