Skip to content

Instantly share code, notes, and snippets.

@vyach-vasiliev
Created March 5, 2022 18:31
Show Gist options
  • Save vyach-vasiliev/9095599bbce7c25b71271cb0a99fbc22 to your computer and use it in GitHub Desktop.
Save vyach-vasiliev/9095599bbce7c25b71271cb0a99fbc22 to your computer and use it in GitHub Desktop.
Sorting list by values from another list
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