简体   繁体   中英

How to sort 2D list by columns?

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?

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)]

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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM