用python编写一些代码来计算基本函数。我有一个带有一些值的二维数组,我想将该函数应用于这些值中的每一个,并得到一个新的二维数组:
import numpy as N
def makeGrid(dim):
''' Function to return a grid of distances from the centre of an array.
This version uses loops to fill the array and is thus slow.'''
tabx = N.arange(dim) - float(dim/2.0) + 0.5
taby = N.arange(dim) - float(dim/2.0) + 0.5
grid = N.zeros((dim,dim), dtype='float')
for y in range(dim):
for x in range(dim):
grid[y,x] = N.sqrt(tabx[x]**2 + taby[y]**2)
return grid
import math
def BigGrid(dim):
l= float(raw_input('Enter a value for lambda: '))
p= float(raw_input('Enter a value for phi: '))
a = makeGrid
b= N.zeros ((10,10),dtype=float) #Create an array to take the returned values
for i in range(10):
for j in range (10):
b[i][j] = a[i][j]*l*p
return b
if __name__ == "__main__":
''' Module test code '''
size = 10 #Dimension of the array
newGrid = BigGrid(size)
newGrid = N.round(newGrid, decimals=2)
print newGrid
但我得到的只是错误信息
Traceback (most recent call last):
File "sim.py", line 31, in <module>
newGrid = BigGrid(size)
File "sim.py", line 24, in BigGrid
b[i][j] = a[i][j]*l*p
TypeError: 'function' object has no attribute '__getitem__'
请帮忙。
您没有调用
makeGrid()
,而是将函数对象本身分配给a
:正如其他人所说,您需要正确调用makeGrid。。。。与fyi一样,这是Python中常见的错误,通常意味着变量不是您认为的类型(在本例中,您期望的是一个矩阵,但得到的是一个函数)
你好像忘记了一对括号:
你现在拥有的:
只是给
makeGrid
函数取别名,而不是调用它。然后,当您尝试索引到a
时,如下所示:它试图索引到一个函数中,该函数没有用括号表示法索引所需的^{} magic method。
相关问题 更多 >
编程相关推荐