【问题标题】:Error iterating over a list 'TypeError: cannot unpack non-iterable object'迭代列表时出错“TypeError:无法解压不可迭代的对象”
【发布时间】:2020-07-12 05:08:32
【问题描述】:

我正在编写一个 Python 脚本来用 SciPy 的 odeint 求解某个微分方程。我只是复制了文档页面上的示例:

def pend(y,t,b,c):
    theta, omega = y
    dydt = [omega, -b*omega -c*np.sin(theta)]
    return dydt
b = 0.25
c = 5.0

y0 = [np.pi-0.1,0.0]
t = np.linspace(0,10,101)
sol = odeint(pend, y0, t, args = (b,c))
plt.plot(t,sol[:,1])
plt.plot(t,sol[:,0])

这一切正常,但当我尝试使用 Lotka-Volterra 系统时,代码会崩溃:

def F(t,n,a,b,c,d):
    x, y = n
    deriv = [a*x-b*x*y,c*x*y-d*y]
    return deriv

t = np.linspace(0,100,100)
a = 1.1
b= 0.4
c = 0.1
d = 0.4
n0 = [10,10]
sol = odeint(F,n0,t,args = (a,b,c,d))

这会返回一个类型错误

<ipython-input-14-ea2a41feaef2> in F(t, n, a, b, c, d)
     1 def F(t,n,a,b,c,d):
----> 2     x, y = n
     3     deriv = [a*x-b*x*y,c*x*y-d*y]
     4     return deriv
     5 

TypeError: cannot unpack non-iterable float object


谁能帮我看看我错过了什么?具体来说,如果第二个代码是用相同的结构编写的,为什么示例代码可以工作。谢谢!

【问题讨论】:

    标签: python scipy


    【解决方案1】:

    我假设,在这一行中传递的参数的顺序不正确:

    sol = odeint(F,n0,t,args = (a,b,c,d))
    

    不应该是:

    sol = odeint(F,t,n0,args = (a,b,c,d))
    

    或者,您可以将函数定义中的参数顺序交换为:

    def F(n,t,a,b,c,d):
    

    【讨论】:

      猜你喜欢
      • 2020-01-28
      • 2021-06-06
      • 2020-04-08
      • 2021-05-25
      • 1970-01-01
      • 2022-01-23
      • 2021-11-01
      • 2019-11-25
      • 1970-01-01
      相关资源
      最近更新 更多