在Python中有什么方法可以追加?

Rau*_*ani 2 python append matrix behind

我有一个矩阵:

[[1 2 3],
[4 5 6], 
[7 8 9]]  
Run Code Online (Sandbox Code Playgroud)

我需要创建一个新矩阵:

[[7 4 1],
[8 5 2],
[9 6 3]]
Run Code Online (Sandbox Code Playgroud)

我试过了

new_matrix = [[1]]
new_matrix.append(matrix[1][0])
Run Code Online (Sandbox Code Playgroud)

得到一个new_matrix = [4 1]而不是new_matrix =[1 4]

如果您需要更多说明,请询问.

cge*_*cge 8

是.使用new_matrix.insert(0,matrix[1][0]).

insert(position,value)允许您将对象插入列表中的指定位置.在这种情况下,由于您要在开头插入数字,因此位置为零.

但是请注意,如果new_matrix有n个元素,则需要O(n)时间.如果new_matrix有100个元素,那么在开头添加一些元素需要花费十倍的时间比它有10个元素.这比在列表末尾添加一些东西要慢得多,这通常需要O(1):它应该是快速的new_matrix有多大.有关python操作的时间复杂性的更多信息,请参见此处.如果您经常在列表的开头添加元素,则可能需要考虑是否可以撤消正在执行的操作.

另外,请注意你做事的方式,这将给你一个[4,[1]]的new_matrix.我不太确定你想要什么:如果你想要最终结果,那么你需要new_matrix = [1].如果您的代码是正确的(new_matrix = [[1]]),并且您想要[[4,1]],那么您需要这样做new_matrix[0].insert(0,4).如果你愿意[[4],[1]],你需要做new_matrix.insert(0,[4]),等等.

顺便说一句,既然你似乎在用矩阵做事,你考虑过使用numpy吗?


(我想指出的是,如果这个答案看起来有点偏离主题,那是因为这个问题被编辑成与最初提出的问题完全不同.)

至于新问题:虽然Stefan的答案很好,但你可能会给自己太多的工作.很明显,你试图实现类似矩阵转置的东西,除了镜像.如果你正在做那些操作,Numpy容易,更快.在这种情况下,使用numpy数组,您只需要执行以下操作:

import numpy as np # import numpy
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Here's your matrix
new_matrix_1 = matrix[::-1,:] # Here's your matrix with all the rows reversed: [[7,8,9],[4,5,6],[1,2,3]]
new_matrix = new_matrix_1.T # Here's the transpose of that, which is what you want.
Run Code Online (Sandbox Code Playgroud)

虽然这只是一件事,但这会让你做的一切变得更轻松.例如,算术实际上将起作用:new_matrix+matrix,2*new_matrix等等.您必须手动实现此操作.