内部列表的Python排序列表

时间:2013-04-21 20:51:40

标签: python list sorting python-2.7

假设一个列表列表,如下所示:

lists=[[3,2,1,4],[6,4,2,8],[9,6,3,12]]

如果我想按lists[0]排序,则应按如下方式排序:

lists=[[1,2,3,4],[2,4,6,8],[3,6,9,12]] #can be another variable

列出三个清单:

list1,list2,list3=(list(t) for t in zip(*sorted(zip(lists[0], lists[1],lists[2]))))

但这是一个特定的解决方案,列表中的列表可能更为通用 lists变量的创建方式如下:

lists = [[] for x in xrange(n)]

并附上了数值。

实际上所有的值都是数字(浮点数或整数),但这可能会更好地解释它。

lists=[[3,2,1,4],["three","two","one","four"],["tres","dos","uno","cuatro"]]

我想知道如何排序并最终得到这个:

[[1,2,3,4],["one","two","three","four"],["uno","dos","tres","cuatro"]]

1 个答案:

答案 0 :(得分:4)

这可能是最不可能使用Schwartzian变换的情况

>>> lists=[[3,2,1,4],["three","two","one","four"],["tres","dos","uno","cuatro"]]
>>> [[x for i, x in sorted(zip(lists[0], sublist))] for sublist in lists]
[[1, 2, 3, 4], ['one', 'two', 'three', 'four'], ['uno', 'dos', 'tres', 'cuatro']]