2011-07-01 67 views
4

。例如对应:排序表中的列(列出的清单),同时保留行

list1 = ['c', 'b', 'a'] 
list2 = [3, 2, 1] 
list3 = ['11', '10', '01'] 
table = [list1, list2, list3] 

我想相对于第一列(列表1)进行排序,但我像最后的命令仍然保留行(所以排序后,我仍然有一条'b',2,'10')。在这个例子中,我可以单独对每个列表进行排序,但使用我的数据我不能这样做。 pythonic方法是什么?

回答

6

一个快速的方法是使用zip

>>> from operator import itemgetter 
>>> transpose = zip(*table) 
>>> transpose.sort(key=itemgetter(0)) 
>>> table = zip(*transpose) 
>>> table 
[('a', 'b', 'c'), (1, 2, 3), ('01', '10', '11')] 
+2

在[FMc]上R a一下(http://stackoverflow.com/questions/6542399/sorting-columns-in-a-table-list-of-lists-whilst-preserving-the-correspondence-o/6542819 #6542819)使用'sorted',这里是上面的一行:'table = zip(* sorted(zip(* table),key = itemgetter(0)))''。 – senderle

1
# Get a list of indexes (js), sorted by the values in list1. 
js = [t[1] for t in sorted((v,i) for i,v in enumerate(list1))] 

# Use those indexes to build your new table. 
sorted_table = [[row[j] for j in js] for row in table] 

有关Python如何排序元组的列表信息,请参阅this question

相关问题