Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Python Columns with corresponding rows

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?

like image 662
Meric Ozcan Avatar asked Jul 22 '17 12:07

Meric Ozcan


1 Answers

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)))))
like image 138
zwer Avatar answered Nov 09 '22 01:11

zwer