python bad operand type for unary -: 'NoneType'

不问归期 提交于 2021-02-08 11:16:29

问题


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'


回答1:


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'>


来源:https://stackoverflow.com/questions/39659023/python-bad-operand-type-for-unary-nonetype

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!