对矩阵的列进行排序(python3)
我有一段用Python 3写的代码,用来输入一个矩阵:
matrix = []
loop = True
while loop:
line = input()
if not line:
loop = False
values = line.split()
row = [int(value) for value in values]
matrix.append(row)
这段代码会生成一个像这样的矩阵:
9 2 6 3
0 3 4 2
2 1 1 0
我想问的是;我该如何用像希尔排序这样的排序算法来对所有列进行排序:
inc = len(thelist) // 2
while inc:
for i, el in enumerate(thelist):
while i >= inc and thelist[i - inc] > el:
thelist[i] = thelist[i - inc]
i -= inc
thelist[i] = el
inc = 1 if inc == 2 else int(inc * 5.0 / 11)
这样就能得到排序后的矩阵:
0 1 1 0
2 2 4 2
9 3 6 3
到目前为止,我尝试过分割列:
col = line.split(line, ',')
但没有成功。我想在不使用像numpy这样的外部库的情况下做到这一点。
谢谢
3 个回答
0
你可以用下面的代码来转置你的矩阵:
def transpose(matrix):
return map(list, zip(*matrix))
这样,如果你有一个按行排序的代码,你的排序就可以用来排序列(这里我用了内置的 sorted
函数):
transpose(sorted(transpose(matrix))
如果你想独立地对每一列的元素进行排序,你只需要对列使用排序的映射功能就可以了。
transpose(map(sorted, transpose(matrix)))
0
很遗憾,Python在按列对列表中的列表进行排序时非常麻烦(使用numpy数组会简单很多)。假设你不想用或者不能使用它们,你可以先把你的矩阵转置,然后对得到的行进行排序,最后再进行第二次转置。
sort_func就是你定义的排序函数(我用的是sorted)。
比如,
>>> a = [[1,3,5],[0,9,5],[2,1,5]]
>>> at = [[row[i] for row in a] for i in range(len(a))]
>>> ats = [sort_func(row) for row in at]
>>> atst = [[row[i] for row in ats] for i in range(len(ats))]
>>> atst
[[0, 1, 5], [1, 3, 5], [2, 9, 5]]
>>> a
[[1, 3, 5], [0, 9, 5], [2, 1, 5]]
如果你不介意使用numpy数组,我建议你可以做类似下面的操作:
a = np.array(a)
for j in range(a.shape[1]):
a[:,j] = sort_func(a[:,j])
0
使用下面的代码:
def sortmatrix(matrix):
length, width = len(matrix[0]), len(matrix)
dup = [item for sub in matrix for item in sub]
dup = sorted(dup)
i = 0
new_list = [dup[i:i+length] for i in range(len(dup)) if i %length == 0]
return new_list
这段代码运行的结果是:
>>> def sortmatrix(matrix):
... length, width = len(matrix[0]), len(matrix)
... dup = [item for sub in matrix for item in sub]
... dup = sorted(dup)
... i = 0
... new_list = [dup[i:i+length] for i in range(len(dup)) if i %length == 0]
... return new_list
... ...
>>> sortmatrix([['9', '2', '6', '3'], ['0', '3', '4', '2'], ['2', '1', '1', '0']])
[['0', '0', '1', '1'], ['2', '2', '2', '3'], ['3', '4', '6', '9']]
>>>