【问题标题】:How to convert a list to an array as there is a need to take transpose in Python?由于需要在 Python 中进行转置,如何将列表转换为数组?
【发布时间】:2021-12-30 13:38:12
【问题描述】:

我有一个 u0 列表,其中附加了值,然后我必须对 u0 进行转置,但是当我这样做时,我仍然得到一个行矩阵,但我想将它显示为一列矩阵。从其他答案中,我了解到计算没有区别,但我希望它显示为列矩阵,这可以进一步用于计算。 x_mirror 也是一个列表。

u0 = []
for p in range(0,tpts):                              #initial condition at t = 0
    ts =  ((np.exp(alpha*((x_mirror[p]-x_start)**2))*(np.cos(k0*(x_mirror[p]-x_start)))))
    u0.append(ts)

非常感谢任何帮助。

【问题讨论】:

  • “显示为列矩阵”是什么意思?您是指np.shape 还是格式方面的意思?
  • 我的意思主要是形状

标签: python arrays multidimensional-array transpose


【解决方案1】:

根据已经存在的 stackoverflow 帖子 (here),您可以执行以下操作

import numpy as np
list1 = [2,4,6,8,10]

array1 = np.array(list1)[np.newaxis]
print(array1)
print(array1.transpose())

对于上面的代码,你可以在这里看到输出:

【讨论】:

    【解决方案2】:

    如果你只是想让它垂直显示,你可以将你的类创建为list的子类。

    class ColumnList(list):
        def __repr__(self):
            parts = '\n '.join(map(str, self))
            r = f'[{parts}]'
            return r
    
    u0 = ColumnList()
    for p in range(0,tpts):                              #initial condition at t = 0
        ts =  ((np.exp(alpha*((x_mirror[p]-x_start)**2))*(np.cos(k0*(x_mirror[p]-x_start)))))
        u0.append(ts)
    
    # displays vertically:
    u0
    

    【讨论】:

    • 感谢您的帮助。假设如果我们希望将转置矩阵用于进一步的计算,尤其是矩阵乘法,我们该怎么做呢?答案会有很大不同吗?
    【解决方案3】:

    你可以使用reshape -

    u0 = [1, 2, 3]
    np_u0_row = np.array(u0)
    np_u0_col = np_u0_row.reshape((1, len(u0)))
    print(np_u0_col.shape)
    # (1, 3)
    

    【讨论】:

      【解决方案4】:

      不确定我的问题是否正确,但请尝试将其转换为具有正确行数且只有一列的二维数组。

      rowMatrix = [1, 2, 3, 4, 5]
      columnMatrix = [[1], [2], [3], [4], [5]]
      

      【讨论】:

      • 但是这种情况下怎么做呢?我实际上是在列表中附加值我们如何在数组中做到这一点?
      • 你的解决方案是什么?
      猜你喜欢
      • 2017-10-14
      • 2017-11-04
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 2021-01-06
      • 2017-06-07
      • 2019-03-12
      相关资源
      最近更新 更多