看来您需要调试帮助。你说“它一直给我这个错误”,这意味着你不理解这个错误,你继续尝试同样的事情,或者类似的事情。这就像把你的头撞在墙上然后抱怨它一直很痛:)
您的功能 - 范围更小。在代码工作之前无需使用大范围:
In [525]: def func(E):
...: for i in range(1,4):
...: y[i+1] = 2 * y[i] - y[i-1] + (-2*(dx**2) * (E - V) * y[i])
...: return y[i+1]
...:
In [526]: dx=0.001
In [527]: y = np.arange(6)
In [528]: V = range(1,4)
让我们尝试仅使用 1 个数字的功能。在通过地图通过整个范围之前,这必须有效。
In [529]: func(1)
Traceback (most recent call last):
File "<ipython-input-529-9ed089a72395>", line 1, in <module>
func(1)
File "<ipython-input-525-9fc020925ab9>", line 3, in func
y[i+1] = 2 * y[i] - y[i-1] + (-2*(dx**2) * (E - V) * y[i])
TypeError: unsupported operand type(s) for -: 'int' and 'range'
这就是您不断遇到的错误。该错误与map(func, V)无关。
那么range 在您的函数中在哪里? V 是 range,对吧?所以该函数正在尝试做:
In [530]: 1 - V
Traceback (most recent call last):
File "<ipython-input-530-aa851a38238f>", line 1, in <module>
1 - V
TypeError: unsupported operand type(s) for -: 'int' and 'range'
同样的错误。当您在长计算中遇到错误时,您需要隔离出现问题的步骤。您可以将计算拆分为多行,或者在这种情况下,请注意错误消息。
如果我们将范围扩展为完整列表会怎样:
In [531]: V = list(V)
In [532]: 1 - V
Traceback (most recent call last):
File "<ipython-input-532-51e70f02e628>", line 1, in <module>
1 - V
TypeError: unsupported operand type(s) for -: 'int' and 'list'
也没有为列表定义加法(期望list1+list2 连接)
为numpy 数组定义逐元素加法:
In [533]: V = np.array(V)
In [534]: 1 - V
Out[534]: array([ 0, -1, -2])
但是当我们使用该数组 V 尝试您的函数时:
In [535]: func(1)
TypeError: only size-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<ipython-input-535-9ed089a72395>", line 1, in <module>
func(1)
File "<ipython-input-525-9fc020925ab9>", line 3, in func
y[i+1] = 2 * y[i] - y[i-1] + (-2*(dx**2) * (E - V) * y[i])
ValueError: setting an array element with a sequence.
E-V 是一个数字数组,如 [534] 所示。这意味着完整的计算也会产生一个数组。如果这不明显,那么您还没有阅读足够基本的numpy。
但是y[i+1] 是一个号码的插槽。因此出现 ValueError。
此时我将退出,因为我不知道您要做什么,也不会尝试猜测。