Update and rename sort_list_based_on_another_list.md to sort_by_indexes.md

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-09-07 09:58:39 +03:00
committed by GitHub
parent a1357e543d
commit 6f8dd5e941
2 changed files with 20 additions and 19 deletions

View File

@ -0,0 +1,20 @@
---
title: sort_by_indexes
tags: list,sort,intermediate
---
Sorts one list based on another list containing the desired indexes.
Use `zip()` and `sorted()` to combine and sort the two lists, based on the values of `indexes`.
Use a list comprehension to get the first element of each pair from the result.
```py
def sort_by_indexes(lst, indexes):
return [val for _, val in sorted(zip(indexes, lst), key = lambda x: x[0])]
```
```py
a = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk']
b = [3, 2, 6, 4, 1, 5]
sort_by_indexes(a, b) # ['apples', 'bread', 'eggs', 'jam', 'milk', 'oranges']
```

View File

@ -1,19 +0,0 @@
---
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(list_to_sort, index_list):
return [val for i, val in sorted(zip(index_list, 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']
```