2011-07-21 49 views
1

我在Python中使用了列表/數組/矩陣的問題。在列表中添加一個新的列(數組)

我有一個矩陣(或數組,如果需要的話)的列表,我想爲它們中的每一個添加一列(相同數量的行)的新列。我怎樣才能做到這一點??

我有一些事情,並沒有得到任何成功。

感謝您的幫助。

下面是一個例子:

>>> A=[mat([[1,2,3],[4,5,6],[7,8,9]]),mat([[1,0,0],[0,1,0],[0,0,1]])] 
>>> A 
[matrix([[1, 2, 3], 
     [4, 5, 6], 
     [7, 8, 9]]), matrix([[1, 0, 0], 
     [0, 1, 0], 
     [0, 0, 1]])] 

使用你們告訴

>>> A = np.hstack((A, np.ones((A.shape[0],1),dtype=A.type))) 

Traceback (most recent call last): 
    File "<pyshell#14>", line 1, in <module> 
    A = np.hstack((A, np.ones((A.shape[0],1),dtype=A.type))) 
AttributeError: 'list' object has no attribute 'shape'` 
+2

向我們展示您嘗試過的內容。 – agf

回答

3

實施例用於2D NumPy的ndarray:

>>> m = np.arange(12).reshape(3,4) 
>>> m = np.hstack((m, np.ones((m.shape[0], 1), dtype=m.dtype))) 
>>> m 
array([[ 0, 1, 2, 3, 1], 
     [ 4, 5, 6, 7, 1], 
     [ 8, 9, 10, 11, 1]]) 

編輯:它適用於基體中的相同。對於矩陣列表,您可以使用for循環:

>>> matrices = [np.matrix(np.random.randn(3,4)) for i in range(10)] 
>>> for i, m in enumerate(matrices): 
...  matrices[i] = np.hstack((m, np.ones((m.shape[0], 1), dtype=m.dtype))) 
+0

這真的不起作用,看編輯的問題 –

+0

沒關係,第二部分工作,在編輯之前沒看過 –

1

2D柱陣列的答案:

for matrix in matricies: 
    matrix.append([1,] * len(matrix[0])) 

2D行數組:

for matrix in matricies: 
    for row in matrix: 
     row.append(1)