0

I'm working with a 2D list of numbers similar to the example below I and am trying to reorder the columns:

D C B A

1 3 2 0

1 3 2 0

1 3 2 0

The first row of the list is reserved for letters to reference each column. How can I sort this list so that these columns are placed in alphabetical order to achieve the following:

D C B A    A B C D

1 3 2 0    0 2 3 1

1 3 2 0    0 2 3 1

1 3 2 0    0 2 3 1

I've found examples that make use of lambdas for sorting, but have not found any similar examples that sort columns by characters.

I'm not sure how to achieve this sorting and would really appreciate some help.

1
  • 1
    Can you show us what code you've got so far? Commented Jan 17, 2016 at 23:33

2 Answers 2

1

zip() the 2D list, sort by the first item, then zip() again.

>>> table = [['D', 'C', 'B', 'A',],
...          [1, 3, 2, 0,],
...          [1, 3, 2, 0],
...          [1, 3, 2, 0]]
>>> for row in zip(*sorted(zip(*table), key=lambda x: x[0])):
...     print(*row)
...
A B C D
0 2 3 1
0 2 3 1
0 2 3 1
Sign up to request clarification or add additional context in comments.

Comments

0

Assume values stored row-by-row in list, like that:

a = [['D', 'C', 'B', 'A'],
     ['1', '3', '2', '0'],
     ['1', '3', '2', '0']]

To sort this array you can use following code:

zip(*sorted(zip(*a), key=lambda column: column[0]))

where column[0] - value to be sorted by (you can use column1 etc.)

Output:

[('A', 'B', 'C', 'D'),
 ('0', '2', '3', '1'),
 ('0', '2', '3', '1')]

Note: If you are working with pretty big arrays and execution time does matter, consider using numpy, it has appropriate method: NumPy sort

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.