对表中的列(列表列表)进行排序,同时保留行的对应关系

时间:2011-07-01 00:10:42

标签: python list sorting

例如:

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

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

2 个答案:

答案 0 :(得分: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')]

答案 1 :(得分: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