简体   繁体   English

Python 2d列表按列标题排序

[英]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: 列表中的第一行是标题行:C,A,D,B。如何更改此项,以便各列按顺序排列,以便显示:

['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 我希望标题按A,B,C,D的顺序排列,但也将标题下面的列移动

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 : 您可以使用sortedzip ,首先创建列有清单zip(*a)与在排序(基于第一指标) sorted ,并再次转换到第一状态,以zip和索引转换成列表与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. 您可以使用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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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