Reputation: 23
I would like to take a 2D list like this:
initial_table = [
[1, 2, 3],
[5, 4, 3],
[2, 3, 4]
]
and sort each column vertically to get:
sorted_table = [
[1, 2, 3],
[2, 3, 3],
[5, 4, 4]
]
Edit: I have tried using sorted_table = sorted(initial_table, key=lambda a:a[0])
but that just sorts one column, is there a way to make it sort multiple?
Upvotes: 1
Views: 232
Reputation: 11400
numpy is your friend!
import numpy as np
initial_table = [
[1, 2, 3],
[5, 4, 3],
[2, 3, 4]
]
np.sort(np.array(initial_table), axis=0)
>> array([[1, 2, 3],
[2, 3, 3],
[5, 4, 4]])
Upvotes: 2
Reputation: 5387
Transpose using zip(*l)
to get a list of columns, then sort each individual column, then transpose back:
list(zip(*(sorted(col) for col in zip(*initial_table))))
Step by step output:
print(list(zip(*initial_table)))
# [(1, 5, 2), (2, 4, 3), (3, 3, 4)]
print([sorted(l) for l in zip(*initial_table)])
# [[1, 2, 5], [2, 3, 4], [3, 3, 4]]
print(list(zip(*(sorted(col) for col in zip(*initial_table)))))
# [(1, 2, 3), (2, 3, 3), (5, 4, 4)]
Upvotes: 3