【问题标题】:unsupported operand type(s) for *: 'float' and 'NoneType' [closed]* 不支持的操作数类型:“float”和“NoneType”[关闭]
【发布时间】:2019-08-08 13:05:25
【问题描述】:

运行代码时出现这样的错误

unsupported operand type(s) for *: 'float' and 'NoneType'

如果我删除这部分

Total = Total* exp
    Total = 1-Total
    possition = possition + 1 

有这样的错误

IndexError: index 4 is out of bounds for axis 1 with size 4

代码:

import random

def getsys():
    row = ''
    for i in range(0 , 8):
        randintt = str(random.randint(0 , 4))
        row += randintt
    return row


def getx():
    x = []
    for i in range(0,14):
        mysys = getsys()
        x.append(mysys)

    return x 

y = getx()
print (y)
import initialsys
import numpy as np

R = np.array([[0.90 , 0.93,0.91 , 0.95],
               [0.95 , 0.94, 0.93, 0],
               [0.85 , 0.90 , 0.87 , 0.92],
               [0.83 , 0.87 , 0.85 , 0 ],
               [0.94 , 0.93 , 0.95 , 0],
               [0.99 , 0.98 , 0.97 , 0.96],
               [0.91 , 0.92 , 0.94 , 0],
               [0.81 , 0.90 , 0.91 , 0],
               [0.97 , 0.99 , 0.96 , 0.91],
               [0.83 , 0.85 , 0.90 , 0],
               [0.94 , 0.95 , 0.96 , 0],
               [0.79 , 0.82 , 0.85 , 0.90],
               [0.98 , 0.99 , 0.97 , 0],
               [0.85 , 0.92 , 0.95 , 0.99]
              ])

def expression(r ,possition , char ):
    exp = 1-r[possition , int(char)]


x = initialsys.getx()
possition = 0
Total = 1
Total = float(Total)
char = ""
for row in x :
    for char in row :
        if char!= 0 :
            exp = expression(R , possition , char)
            Total = Total* exp
    Total = 1-Total
    possition = possition + 1 

【问题讨论】:

  • 你在expression中没有return,所以它返回默认的None
  • 函数def expression没有返回exp的值。

标签: python numpy math data-science


【解决方案1】:

您的函数def expression(r ,possition , char ) 不返回任何内容。

你应该这样写:

def expression(r ,possition , char ):
    return 1-r[possition , int(char)]

【讨论】:

    【解决方案2】:

    几个变化。

    • 您在expression 中缺少return 语句
    • random.randint(0 , 4) 应该是 random.randint(0 , 3)

    例如:

    def expression(r ,possition , char ):
        exp = 1-r[possition , int(char)]
        return exp
    

    def getsys():
        row = ''
        for i in range(0 , 8):
            randintt = str(random.randint(0 , 3))
            row += randintt
        return row
    

    【讨论】:

    • 查看此链接以了解scope 的概念:pythonspot.com/scope
    • @Rakesh 我将 4 更改为 3 但 IndexError: index 4 is out of bounds for axis 1 with size 4 错误仍然存​​在
    【解决方案3】:

    我将 4 更改为 3,但 IndexError: index 4 is out of bounds for axis 1 with size 4 错误仍然存​​在

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-06
      • 2014-03-28
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多