[英]Unpacking a list in python using .T?
我正在使用scipy的方法integration.odeint解決二階LDE。 該方法要求將該方程以兩個未知數中的兩個一階方程組的形式放置。 方法
odeint(system_matrix,initial_conditions_matrix,time_values)
在每個時間點以time_values輸出解向量。 解向量實際上是[u,u']的形式,其中u是我感興趣的變量。因此,我只想繪制u。 我在網上發現完成此操作的一種方法是使用
u,u'=odeint(system_matrix,initial_conditions_matrix,time_values).T
但我不明白為什么會這樣,.T到底意味着什么?
odeint(system_matrix,initial_conditions_matrix,time_values)
是2列的矩陣。
為了能夠獲得第一列,請首先使用.T
(轉置),然后可以解壓縮,因為元素的方向是您想要的。
順便說一句,我懷疑u'
是一個有效的變量名。 我會做:
u,_ = odeint(system_matrix,initial_conditions_matrix,time_values).T
因為第二值對您而言並不重要。
我想到的示例是:
>>> sol = odeint(pend, y0, t, args=(b, c))
The solution is an array with shape (101, 2). The first column is theta(t), and the second is omega(t). The following code plots both components.
>>>
>>> import matplotlib.pyplot as plt
>>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
>>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
sol[:,0]
選擇sol
的第一列
拆包通常與返回元組的函數一起使用,例如:
def foo():
....
return [1,2,3],{3:3}
x, y = foo()
應該以x
為列表結尾, y
以字典結尾。
但是它可以與任何迭代一起使用,只要提供術語數量匹配即可。 例如,可以將2行陣列拆包為2個陣列。
In [1]: x, y = np.arange(6).reshape(2,3)
In [4]: x,y
Out[4]: (array([0, 1, 2]), array([3, 4, 5]))
如果創建(3,2)數組,則需要x,y,z= ...
或.T
。
因為我們可以索引列和行,所以在numpy
沒有太多使用解包。 通常,我們有太多行要解壓。 但它的工作原理與基本的Python預期相同。
出於好奇, transpose
在元組上起作用
In [6]: np.transpose((x,y))
Out[6]:
array([[0, 3],
[1, 4],
[2, 5]])
實際上,這在np.argwhere
使用, np.argwhere
產生的索引的元組np.where
為具有與維相同的列數的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.