python中的函数无法识别_函数中无法识别main中定义的Numpy数组

I define and use a 2 dimensional numpy array in the program main function. A function called within main then tries to modify the numpy array without success. The array is declared as global in the second function but I still get the following error:

必须在main函数中将其声明为global。否则,您只是在创建一个局部变量,而不是全局变量。无论是否使用global,都不能访问另一个函数的局部变量;只能访问全局变量。在I thought that you could read a variable from main within a function without calling it global but that if you modified it within the function you had to declare it global in the function.

很接近真实……但是创建它就等于修改了它。在

所以,与其这样:def sub():

global name_of_array

return name_of_array[0, 0]

def main():

name_of_array = np.zeros((2, 2))

sub()

…这样做:

^{pr2}$

不过,还有一个更好的解决方案:只需将数组作为参数传递,而不是使用全局:def sub(name_of_array):

return name_of_array[0, 0]

def main():

name_of_array = np.zeros((2, 2))

sub(name_of_array)

如果你避免了因为你来自C++之类的语言,担心这会浪费大量的时间和内存拷贝整个数组,那么Python就不可能这样工作。(在C++术语中,所有变量都通过使用引用参数的方式传递……虽然这个术语在Python中可能会误导。)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值