我如何更正我的代码,以便能够对其元素进行排序,根据这些元素,在最接近其子列表开头的元素中,规范向量的值等于1.0(忽略第一个子列表,这是带有标题的子列表,尽管这也会根据其他子列表中元素1.0的位置改变位置),从而保留?
matrix = [['B', 'X1', 'X2', 'X3', 'X4', 'X5', 'U1', 'U2'], [8, 2.0, 1.0, -1.0, 0, 0, 1.0, 0], [2, 1.0, 1.0, 0, 1.0, 0, 0, 0], [8, 1.0, 2.0, 0, 0, -1.0, 0, 1.0]]
matrix_aux = [['X4', 'U1', 'U2'], [0, 1.0, 0], [1.0, 0, 0], [0, 0, 1.0]]
#Extract the first title sublist
titles = matrix_aux.pop(0)
#Create a list of tuples, and sort it
tuple_list = [(sublist.index(1.0), sublist) for sublist in matrix_aux]
sorted_tuples = sorted(tuple_list, key=lambda x: x[0])
#Rebuild the sorted array
matrix_aux_ord = [[titles[i] for i in range(len(titles))]] + [sublist for _, sublist in sorted_tuples]
print(matrix_aux_ord)
for row in matrix_aux_ord: print(row) #print in matrix format
the problem now with my code是它忘记了对标题或标题行['X4', 'U1', 'U2']
进行排序,错误地打印了该矩阵
[['X4', 'U1', 'U2'], [1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]
如果它保持一致性,而不是这个
[['U1', 'X4', 'U2'], [1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]
然后,拥有这两个矩阵,构建名为new_matrix
的新矩阵,其中我将在matrix
前面添加一列,也就是说,我将向组成matrix
行的每个子列表添加一个元素,向名为matrix
的矩阵的第一个子列表添加一个元素,并在名为matrix
的矩阵的其余子列表中添加一个‘X’作为第一个元素,并以有序的方式将名为matrix_aux_ord
的矩阵的第一个子列表的元素添加为第一个元素
matrix = [['B', 'X1', 'X2', 'X3', 'X4', 'X5', 'U1', 'U2'], [8, 2.0, 1.0, -1.0, 0, 0, 1.0, 0], [2, 1.0, 1.0, 0, 1.0, 0, 0, 0], [8, 1.0, 2.0, 0, 0, -1.0, 0, 1.0]]
#If the previous code worked, it would get this array sorted like this...
matrix_aux_ord = [['U1', 'X4', 'U2'], [1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]
#Add the column title or header 'X' to the front of the first sublist of matrix
matrix[0].insert(0, 'X')
因此,最终得到的矩阵correct output,称为new_matrix
,将如下所示:
new_matrix = [['X', 'B', 'X1', 'X2', 'X3', 'X4', 'X5', 'U1', 'U2'], ['U1', 8, 2.0, 1.0, -1.0, 0, 0, 1.0, 0], ['X4', 2, 1.0, 1.0, 0, 1.0, 0, 0, 0], ['U2', 8, 1.0, 2.0, 0, 0, -1.0, 0, 1.0]]
我应该怎么做才能正确地得到matrix_aux_ord
,并用它来得到矩阵new_matrix
,它基本上包括一种组合琥珀矩阵matrix
和matrix_aux_ord
的方法?