I have two unsorted lists, x and y, as follows:
x = ["a", "b", "c", "d", "e"] y = [ 5, 1, 4, 2, 3]
I would like to sort list y two times, one in ascending order and then in descending order. But, in each sorting of y, I need to sort also the corresponding elements of the list x accordingly. Both lists have the same length of items.
I tried with the following code, but it is not working as expected:
def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z print(sort_list(x, y))
Expected output: in case of ascending order
x = [ "b", "d","e", "c", "a"] y = [ 1, 2, 3, 4, 5]
Any help?
Advertisement
Answer
Just zip y
and x
– in this order, so that you can sort the resulting tuples in natural order, by their first item.
You can then sort, and zip again:
x = ["a", "b", "c", "d", "e"] y = [ 5, 1, 4, 2, 3] sorted_y, sorted_x = zip(*sorted(zip(y, x))) print(sorted_x, sorted_y) #('b', 'd', 'e', 'c', 'a') (1, 2, 3, 4, 5)
In reverse order:
sorted_y, sorted_x = zip(*sorted(zip(y, x), reverse=True)) print(sorted_x, sorted_y) # ('a', 'c', 'e', 'd', 'b') (5, 4, 3, 2, 1)