[英]Sort columns of a matrix(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
我的問題是; 我如何通過像shellsort這樣的排序算法對所有列進行排序:
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或其他)的情況下執行此操作。
謝謝
使用以下代碼:
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']]
>>>
不幸的是,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])
您可以使用以下代碼轉置矩陣:
def transpose(matrix):
return map(list, zip(*matrix))
因此,如果您具有按行對矩陣進行排序的代碼,那么排序就可以對列進行排序(我在這里使用了內置的sorted
函數):
transpose(sorted(transpose(matrix))
如果要單獨對每個列的元素進行排序,則可以將排序映射到列上
transpose(map(sorted, transpose(matrix)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.