From 48fc7ebf2935c12b8764d47fe1a42db60d248b22 Mon Sep 17 00:00:00 2001 From: Sahith Kurapati <52966918+Sahith02@users.noreply.github.com> Date: Fri, 19 Jun 2020 17:14:35 +0530 Subject: [PATCH] Added new snippet Added sort_list_based_on_another_list.md snippet. It sorts one list based on another list in python. --- snippets/sort_list_based_on_another_list.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 snippets/sort_list_based_on_another_list.md diff --git a/snippets/sort_list_based_on_another_list.md b/snippets/sort_list_based_on_another_list.md new file mode 100644 index 000000000..137f26b17 --- /dev/null +++ b/snippets/sort_list_based_on_another_list.md @@ -0,0 +1,19 @@ +--- +title: sort_list_based_on_another_list +tags: list,sort,intermediate +--- + +Sorts one list based on given indices in another list and returns the sorted list of values. + +Use list comprehension to get values after using `zip` and `sorted` function based on given `key` with lambda function that returns the index. + +```py +def sort_list_based_on_another_list(to_sort, index_list): + return [val for i, val in sorted(zip(index_list, to_sort), key = lambda x: x[0])] +``` + +```py +a = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk'] +b = [3, 2, 6, 4, 1, 5] +sort_list_based_on_another_list(a, b) # ['apples', 'bread', 'eggs', 'jam', 'milk', 'oranges'] +``` \ No newline at end of file