简体   繁体   中英

Python 2d list sort by colum header

I have a 2d list:

['C', 'A', 'D', 'B'], #header row
['F', 'C', 'F', 'E'], #row 1
['F', 'E', 'F', 'F'], #row 2
['B', 'A', 'F', 'A'],
['A', 'F', 'C', 'E'],
['F', 'F', 'E', 'E'],
['C', 'E', 'F', 'C']

The first row in the list is the header row: C, A, D, B. How can I change this so that the columns are in order so it will appear:

['A', 'B', 'C', 'D'], #header row
['C', 'E', 'F', 'F'], #row 1
['E', 'F', 'F', 'F'], #row 2
['A', 'A', 'B', 'F'], 
['F', 'E', 'A', 'C'],
['F', 'E', 'F', 'E'],
['E', 'C', 'C', 'F']

I want the headers to be in order A,B,C,D but also move the columns underneath with the header

You can use sorted and zip , first create a list of your column with zip(*a) then sort it (based on first index) with sorted , and again convert to first state with zip and convert the indices to list with map :

>>> map(list,zip(*sorted(zip(*a))))
[['A', 'B', 'C', 'D'],
 ['C', 'E', 'F', 'F'],
 ['E', 'F', 'F', 'F'], 
 ['A', 'A', 'B', 'F'], 
 ['F', 'E', 'A', 'C'], 
 ['F', 'E', 'F', 'E'], 
 ['E', 'C', 'C', 'F']]

You could use numpy.

>>> import numpy as np
>>> data = np.array([['C', 'A', 'D', 'B'], #header row
... ['F', 'C', 'F', 'E'], #row 1
... ['F', 'E', 'F', 'F'], #row 2
... ['B', 'A', 'F', 'A'],
... ['A', 'F', 'C', 'E'],
... ['F', 'F', 'E', 'E'],
... ['C', 'E', 'F', 'C']])
>>> data[:,np.argsort(data[0])]  # select sorted indices of first row as column indices.
array([['A', 'B', 'C', 'D'],
       ['C', 'E', 'F', 'F'],
       ['E', 'F', 'F', 'F'],
       ['A', 'A', 'B', 'F'],
       ['F', 'E', 'A', 'C'],
       ['F', 'E', 'F', 'E'],
       ['E', 'C', 'C', 'F']], 
      dtype='|S1')

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