使用python中的值对矩阵进行排序

时间:2015-02-19 09:59:48

标签: python python-2.7 python-3.x

例如我有一个矩阵

a = [[6,8,9],[7,4,3],[1,2,5]]

现在我想对矩阵进行排序,如下所示

a = [[1,2,3],[4,5,6],[7,8,9]]

请帮助我,我是python的新手。

2 个答案:

答案 0 :(得分:2)

对于list-of-list,您可以像这样克隆形状

>>> from itertools import chain
>>> a = [[6,8,9],[7,4,3],[1,2,5]]
>>> it = iter(sorted(chain.from_iterable(a)))
>>> [[next(it) for j in i] for i in a]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

答案 1 :(得分:1)

使用chain.from_iterable

>>> a = [[6,8,9],[7,4,3],[1,2,5]]
>>> from itertools import chain
>>> l = sorted(chain.from_iterable(a))
>>> [l[i:i+3] for i in range(0, len(l),3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]