Python 3:在2D矩阵中对行进行排序,其中列是列表

时间:2012-09-10 12:13:21

标签: python python-3.x

我创建了一个像这样的2D矩阵:

45  67  Row  Fine
25  22  Abe  Real
58  54  Abe  Noon

每列都是一个列表。行中的值连接在一起,因此第三行中索引号为2的值彼此相同。

我想对行进行排序,首先在第三行,然后在第四行,以便它变为:

58  54  Abe  Noon  
25  22  Abe  Real 
45  67  Row  Fine

我不知道该怎么办。我可以对一个列表进行排序,一个列表包含第三列的值。然后找出新的索引号并将它们与旧的比较。然后我也可以调整其他列表,以便所有行再次正确。但是我仍然需要排序第四行。

我看到一些用于对列表here进行排序的代码,但我需要列的行而不是列(如果我理解的话)。

或者创建字典是一种聪明的方式吗?

2 个答案:

答案 0 :(得分:1)

您有一个列列表。要将其添加到行列表中,您只需使用zip

iterable_of_rows = zip(*my_list_of_columns)

将其与典型的方法相结合:

import operator
sorted_list_of_rows = sorted(zip(*my_list_of_columns), key = operator.itemgetter(2,3))
list_of_columns = list(zip(*sorted_list_of_rows))

并测试:

>>> my_list_of_columns = [[45,25,48],[67,22,54],["Row","Abe","Abe"],["Fine","Real","Noon"]]
>>> import operator
>>> sorted_list_of_rows = sorted(zip(*my_list_of_columns), key = operator.itemgetter(2,3))
>>> list_of_columns = list(zip(*sorted_list_of_rows))
>>> list_of_columns
[(48, 25, 45), (54, 22, 67), ('Abe', 'Abe', 'Row'), ('Noon', 'Real', 'Fine')]

答案 1 :(得分:0)

直接使用列列表很麻烦,但您可以使用zip并使用行:

>>> print(data)
[[45, 25, 58], [67, 22, 54], ['Row', 'Abe', 'Abe'], ['Fine', 'Real', 'Noon']]

>>> print(sorted(zip(*data), key=lambda x: (x[2], x[3])))
[(58, 54, 'Abe', 'Noon'), (25, 22, 'Abe', 'Real'), (45, 67, 'Row', 'Fine')]