一元的python错误操作数类型-:'NoneType' [英] python bad operand type for unary -: 'NoneType'
问题描述
我给你发了一个问题,因为我在 python 上有问题,我不明白为什么.我创建了一个函数mut1"来改变列表中的数字(概率为 1/2),无论是加 1 还是减 1,除了 0 和 9:
def mut1 (m):i=np.random.randint(1,3)j=np.random.randint(1,3)如果我==1:如果0<m<9:如果 j==1:米=米+1elif j==2:米=米-1elif m==0:如果 j==1:米=1如果 j==2:米=9elif m==9:如果 j==1:米=0如果 j==2:米=8打印米
mut1 运行良好,例如,如果我创建一个列表 P1:
>>>p1=np.array(range(8),int).reshape((4, 2))
之后,我在列表 p1 中的一个数字(此处为 3)处应用mut1"
>>>mut1(p1[1,1])
但是如果我写:
<预><代码>>>>p1[1,1]=mut1(p1[1,1])我有一条消息错误:
<块引用>回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在<模块>类型错误:long() 参数必须是字符串或数字,而不是'无类型'
发生这种情况是因为您必须让 mut1
返回 numpy.int64
类型的结果.所以我尝试使用以下修改后的代码并成功.
所以你唯一需要改变的是将 print m
替换为 return np.int64(m)
然后应该可以工作了!
使用以下调试代码您将很容易理解为什么会发生这种情况:
<预><代码>>>>类型(p1[1,1])<输入'numpy.int64'>>>>类型(mut1(p1[1,1]))<输入'NoneType'>I send you a question because I have a problem on python and I don't understand why. I created a function "mut1" to change the number inside a list (with a probability to 1/2) either in adding 1 or subtracting 1, except for 0 and 9:
def mut1 (m):
i=np.random.randint(1,3)
j=np.random.randint(1,3)
if i==1:
if 0<m<9:
if j==1:
m=m+1
elif j==2:
m=m-1
elif m==0:
if j==1:
m=1
if j==2:
m=9
elif m==9:
if j==1:
m=0
if j==2:
m=8
print m
mut1 function well, for example, if I create a list P1:
>>>p1=np.array(range(8),int).reshape((4, 2))
After that, I apply "mut1" at a number (here 3) in the list p1
>>>mut1(p1[1,1])
Hovewer if I write:
>>> p1[1,1]=mut1(p1[1,1])
I have a message error:
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: long() argument must be a string or a number, not 'NoneType'
That happens because you have to make your mut1
return an numpy.int64
type of result. So I tried with the following modified code of yours and worked.
>>> import numpy as np
>>> import random
>>>
>>> def mut1 (m):
... i=np.random.randint(1,3)
... j=np.random.randint(1,3)
... if i==1:
... if 0<m<9:
... if j==1:
... m=m+1
... elif j==2:
... m=m-1
... elif m==0:
... if j==1:
... m=1
... if j==2:
... m=9
... elif m==9:
... if j==1:
... m=0
... if j==2:
... m=8
... return np.int64(m)
...
>>> p1=np.array(range(8),int).reshape((4, 2))
>>> mut1(p1[1,1])
2
>>> p1[1,1]=mut1(p1[1,1])
>>>
So the only thing you need to change is to replace print m
with return np.int64(m)
and then should work!
You will easily understand why this happened with the following kind of debugging code:
>>> type(p1[1,1])
<type 'numpy.int64'>
>>> type(mut1(p1[1,1]))
<type 'NoneType'>
这篇关于一元的python错误操作数类型-:'NoneType'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!