【问题标题】:TypeError: 'NoneType' object is not iterable from a beginnerTypeError:“NoneType”对象不能从初学者迭代
【发布时间】:2018-05-18 19:38:22
【问题描述】:

我有一段代码在下一行显示错误

重置购物车是一个如下所示的功能。 谁能告诉我如何解决这个问题?

[pre_s, s, pre_a, a, x, x_dot, theta, theta_dot] = reset_cart(beta)    # reset the cart pole to initial state

类型错误: “NoneType”对象不可迭代

[pre_s, s, pre_a, a, x, x_dot, theta, theta_dot] = reset_cart(beta)
def reset_cart(beta):
pre_s=1
s=1
pre_a=-1  
a=-1   


x = 0
x_dot = 0
theta = 0
theta_dot = 0.01

【问题讨论】:

  • return 语句在哪里?如果您期望返回值,则必须显式返回它们。同样使用列表,嗯,我认为您在 return 语句中需要一个元组,您应该删除属于语法错误的方括号。此外,您在定义函数之前调用了一个函数,这意味着被解释的 python 不会知道它。
  • 用正确的格式标记你的代码和错误
  • 您好先生,非常感谢您的接纳,但我对编码和 python 完全陌生,所以我几乎不明白您要求我做的大部分事情。我应该用其他东西替换括号(也许是括号)。
  • 函数也应该在它被调用的地方之前吗?

标签: python-3.6


【解决方案1】:

您缺少reset_cart 函数的关键部分:返回。

现在,当您的 reset_cart 函数完成时,它刚刚设置的所有变量都会消失,因为它们从未在函数之外被赋值。将值从函数获取到您想要使用它们的任何其他地方的主要方法是使用 return 语句返回它们。

在这种情况下,您尝试将这 8 个元素设置为函数中给定的值,因此返回一个包含这 8 个元素的列表:

def reset_cart(beta):

    pre_s=1
    s=1
    pre_a=-1  #the agent is taking no action
    a=-1

    x = 0
    x_dot = 0
    theta = 0
    theta_dot = 0.01
    return [pre_s, s, pre_a, a, x, x_dot, theta, theta_dot]

有关返回变量和变量范围的更多信息,请参阅:

What is the purpose of the Return statement?

【讨论】:

  • 非常感谢,很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 2017-08-29
相关资源
最近更新 更多