【问题标题】:Python 3: TypeError: can't multiply sequence by non-int of type 'float'Python 3:TypeError:不能将序列乘以“float”类型的非整数
【发布时间】:2019-03-21 01:07:15
【问题描述】:

我的程序包含这个

print("hyy")
print(self.reward, self.gamma, max_val)
print(self.reward + (self.gamma * max_val))

这里self.reward 是-0.25,self.gamma 是1,max_val 是0。

当我运行代码时,我的输出是:

hyy
-0.25 1 0.0
    ans = goal.value_iteration()
  File "/Users/mac/Desktop/MDP-master/value.py", line 237, in value_iteration
    print(self.reward + (self.gamma * max_val))
TypeError: can't multiply sequence by non-int of type 'float'

前两行编译成功。为什么不是我的代码块的第三行?我该如何解决这个问题?

【问题讨论】:

    标签: python typeerror


    【解决方案1】:

    您确定所有变量都是正确的类型吗? 尝试使用 print(type(value))

    来确定这个事实。您始终可以使用强制转换 float(variable)

    【讨论】:

      【解决方案2】:

      self.gamma 不是数字。最可能的是,它是一个字符串。这是一个重现您的错误的最小示例:

      a, b, c = -0.25, '1', 0.0
      
      a + b * c  # TypeError: can't multiply sequence by non-int of type 'float'
      

      定义了将字符串乘以整数,例如'a' * 2 == 'aa',但不是将字符串乘以浮点数,例如 0.0。要转换为数字,您可以使用float:

      a + float(b) * c  # -0.25
      

      【讨论】:

        猜你喜欢
        • 2017-02-04
        • 2010-12-30
        • 2012-10-09
        • 1970-01-01
        • 2013-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-09
        相关资源
        最近更新 更多