【问题标题】:Unpacking a list in python using .T?使用.T在python中解包列表?
【发布时间】:2017-05-29 20:03:56
【问题描述】:

我正在使用 scipy 的方法集成.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 文档中演示的列索引? sol[:,0].

标签: python list numpy scipy


【解决方案1】:

我想到的例子是:

>>> 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.where产生的索引元组转换为列数与维度相同的数组。

【讨论】:

    【解决方案2】:

    odeint(system_matrix,initial_conditions_matrix,time_values) 是一个 2 列矩阵。

    为了能够得到第一列,首先使用.T(转置)然后你就可以解包了,因为元素的方向是你想要的。

    顺便说一句,我怀疑u' 是一个有效的变量名。我会这样做:

    u,_ = odeint(system_matrix,initial_conditions_matrix,time_values).T
    

    因为您对第二个值不感兴趣。

    【讨论】:

    • 添加 unpack 迭代数组的第一个维度。
    • @hpaulj 你能详细说明一下吗?而且您的[:,0] 听起来更好,可以避免换位对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多