Sorting columns in a table (list of lists) whilst preserving the correspondence of the rows
For example:
list1 = ['c', 'b', 'a']
list2 = [3, 2, 1]
list3 = ['11', '10', '01']
table = [list1, list2, list3]
I'd like to sort with respect to the first column (list1), but I'd like the final 开发者_运维问答ordering to still preserve the lines (so after sorting I'd still have a line 'b', 2, '10'). In this example I could just sort each list individually but with my data I can't just do that. What's the pythonic approach?
One quick way would be to use 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')]
# 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]
See this question for information on how Python sorts a list of tuples.
精彩评论