Skip to content

Commit

Permalink
Add reverse to sort_by_indexes
Browse files Browse the repository at this point in the history
  • Loading branch information
Trinityyi committed Oct 16, 2020
1 parent ba66ef8 commit 7501c3f
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions snippets/sort_by_indexes.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
---
title: sort_by_indexes
tags: list,sort,intermediate
tags: list,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.
- Use the `reverse` parameter in `sorted()` to sort the dictionary in reverse order, based on the third argument.

```py
def sort_by_indexes(lst, indexes):
return [val for _, val in sorted(zip(indexes, lst), key = lambda x: x[0])]
def sort_by_indexes(lst, indexes, reverse = False):
return [val for _, val in sorted(zip(indexes, lst), key = lambda x: x[0], reverse = reverse)]
```

```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']
sort_by_indexes(a, b, True) # ['oranges', 'milk', 'jam', 'eggs', 'bread', 'apples']
```

0 comments on commit 7501c3f

Please sign in to comment.