I want to sort column values depending on a row full of int:
cart = [[1, 3, 0, 2], ['olives', 'tomatoes', 'avocado', 'patato']]
and have this
new_cart= [[0, 1, 2, 3], ['avocado', 'olives', 'patato', 'tomatoes' ]]
In other words I want strings to sorted by the integers values which they corresponds:
I found these questions but non of them does what I want:
how to sort 2d array by row in python?
How to sort multidimensional array by column?
A zip-sort-unzip procedure should do the trick:
data = [[1, 3, 0, 2], ['olives', 'tomatoes', 'avocado', 'patato']]
sorted_data = zip(*sorted(zip(data[0], data[1])))
# [(0, 1, 2, 3), ('avocado', 'olives', 'patato', 'tomatoes')]
Or if you want to keep them as lists:
sorted_data = map(list, zip(*sorted(zip(data[0], data[1]))))
# [[0, 1, 2, 3], ['avocado', 'olives', 'patato', 'tomatoes']]
On Python 3.x both zip
and map
return iterators so if you want to 'bake' them into lists just 'cast' them as such, i.e.:
sorted_data = list(map(list, zip(*sorted(zip(data[0], data[1])))))
NOTE: As suggested by JJoao, you can use argument expansion in the inner zip
too instead of explicitly selecting which fields you want to zip
from your list, e.g.:
sorted_data = list(map(list, zip(*sorted(zip(*data)))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With