Python 3 : TypeError: can't multiply sequence by non-int of type 'float'

标签 python typeerror

我的程序包含这个

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'

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

最佳答案

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',但将字符串乘以 float (例如 0.0)则不然。要转换为数字,您可以使用float:

a + float(b) * c  # -0.25

关于Python 3 : TypeError: can't multiply sequence by non-int of type 'float' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52836476/

相关文章:

python - 如何创建具有多种功能的 OpenAI Gym 观察空间

python - IntelliJ + Python 插件 : Python remote interpreter gets created without classpath, 不工作

Python 在迭代过程中就地修改字典条目

ionic-framework - ionic 服务抛出类型错误 : Appscripts. 服务

python - 类型错误:convert() 缺少 1 个必需的位置参数: 'filename'

python - 减少 Django 数据库查询

python - 在 Python 脚本中提升权限

python - 类型错误 : "' types. GenericAlias 的对象不可迭代”

javascript - 仅在匿名函数中未捕获类型错误

python - make_scorer 给出错误 : 'str' object is not callable make_scorer