使用scipy.integrate.odeint和字典[Python]

时间:2016-06-09 22:10:17

标签: python scipy

我试图使用scipy.integrate.odeint解决衰变方程。我试图从字典中获取初始值,但它不起作用,我不确定它是否可以正常工作。以下是我正在使用的代码:

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

def decay(init,t):
    f0 = - init['a']/.5
    f1 = init['a']/.5 - init['b']/.2
    f2 = init['b']/.2
    return [f0,f1,f2]

if __name__ == '__main__':
    init = {'a':5, 'b':0, 'c':0}
    time = np.linspace(0, 10, 101)
    soln  = odeint(decay, init ,time)
    a = soln[:,0]
    b = soln[:,1]
    c = soln[:,2]
    print a
    print b
    print c
    plt.plot(time, a, color = 'g')
    plt.plot(time, b, color = 'r')
    plt.plot(time, c, color = 'b')
    plt.show()

如果不是字典,我会使用如下列表:

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

def decay(init,t):
    a,b,c = init
    f0 = - a/.5
    f1 = a/.5 - b/.2
    f2 = b/.2
    return [f0,f1,f2]

if __name__ == '__main__':
    init = [5,0,0]
    time = np.linspace(0, 10, 101)
    soln  = odeint(decay, init ,time)
    a = soln[:,0]
    b = soln[:,1]
    c = soln[:,2]
    print a
    print b
    print c
    plt.plot(time, a, color = 'g')
    plt.plot(time, b, color = 'r')
    plt.plot(time, c, color = 'b')
    plt.show()

但是,我需要为我的目的使用字典。有没有办法使用字典来调用初始值?

1 个答案:

答案 0 :(得分:1)

如果有效:

init = [5,0,0]
time = np.linspace(0, 10, 101)
soln  = odeint(decay, init ,time)

然后这也应该:

adict = {'a':5, 'b':0, 'c':0}
init = [adict['a'],adict['b'],adict['c']]
time = np.linspace(0, 10, 101)
soln  = odeint(decay, init ,time)

换句话说,无论您从何处获取此词典,都需要将其值转换为列表。

init = adict.values()(或Py3中的list(adict.values()))无效,因为字典以自己的方式对键进行排序:

In [306]: list({'a':5, 'b':0, 'c':0}.values())
Out[306]: [0, 0, 5]

或者对于更长的密钥列表,这可能更简单:

In [307]: adict = {'a':5, 'b':0, 'c':0}
In [308]: init = [adict[k] for k in ['a','b','c']]
In [309]: init
Out[309]: [5, 0, 0]