Created
March 5, 2022 18:31
-
-
Save vyach-vasiliev/9095599bbce7c25b71271cb0a99fbc22 to your computer and use it in GitHub Desktop.
Sorting list by values from another list
This file contains hidden or 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
| main_list = ['a', 'b', 'c', 'd', 'e'] | |
| sort_list = ('b', 'd', 'a', ) | |
| # should be answer | |
| # ['b', 'd', 'a', 'c', 'e'] | |
| # long solution | |
| sorted_list = [y for x in sort_list for y in main_list if x == y] | |
| sorted_list += list(set(main_list) - set(sorted_list)) | |
| # short solution | |
| main_list.sort(key=lambda x: sort_list.index(x) if x in sort_list else len(sort_list)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment