This post discusses how to custom sort one list in python based on the order of elements of another 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] | |
>>> |