2017-04-19 97 views
-1

具有2維數組,我想克隆n *次它的每個項目。這與在兩個維度上放大圖像n次完全相同。 這裏是我的代碼:數組操作:錯誤:'int'對象不支持項目分配

def elargir(a,n) : 
     imag=[a.shape[0]*n,a.shape[1]*n] # Array with the wanted shape 
     for i in range(a.shape[0]): 
      for j in range(a.shape[1]*n): # loops on lines and columns of a 
       imag[i][j]=a[i//5][j//n] 
     return imag 

我創建一個數組

a=np.array([[1,2],[3,4]]) 

,並在其應用功能

elargir (a,5) 

,這裏是thte錯誤

Traceback (most recent call last): 

     File "<ipython-input-14-508f439a1888>", line 1, in <module> 
     elargir (a,5) 

     File "<ipython-input-12-b2382eb5b301>", line 5, in elargir 
     imag[i][j]=a[i//5][j//n] 

    TypeError: 'int' object does not support item assignment 

感謝你的幫助

+0

[類型錯誤: 'INT' 對象不支持項目分配]的可能的複製(http://stackoverflow.com/questions/14805306/typeerror-int-object-does-not-support-item-assignment ) –

+0

這個'imag = [a.shape [0] * n,a.shape [1] * n]'創建了一個包含兩個元素的列表:a.shape [0] * n'和'a.shape [1 ] * N'。 – khelwood

回答

0

imag是一維數組。在for i in range(a.shape[0]):中,您將首先訪問該陣列的第一項,即int,您將進一步嘗試索引j。您示例中的數組與您在第一個代碼塊中獲得的數據不匹配。

import numpy as np 

a = np.arange(9).reshape(3, 3) 
n = 3 

imag=[a.shape[0]*n,a.shape[1]*n] 
print(imag[0]) # The `i` index in your nested for loop 
+0

非常感謝。用np.zeros替換np.array,得到imag數組的版權形狀 –

+0

imag = np.zeros([a.shape [0] * n,a.shape [1] * n]) –

+0

啊,這樣更有意義:)如果你發現這個答案解決了你的問題,那麼請考慮[標記爲正確](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work),讓其他人知道問題解決了。 – roganjosh

相關問題