【问题标题】:Create a matrix with solution arrays in it创建一个包含解决方案数组的矩阵
【发布时间】:2014-06-19 18:29:23
【问题描述】:

我需要在 Python 中创建一个矩阵,其中包含具有这种形式的未知数组 r 的列表:

r_i=[r1,r2,r3,r4,th_12,th_13]

我正在运行带有几个 if 条件的语句,这些条件会在输出中给我一些我从一开始就不知道的 r_i 数组。

我正在寻找一个像 append 这样的函数,我通常使用它来创建一个包含我生成的所有解决方案的向量,但这次每个解决方案都不是单个值,而是一个包含 6 个值的数组而且我无法生成我想要的。

我需要创建一个像这样的矩阵,其中每个 r_1 都有我上面写的代码的形式。

编辑:我想生成一个 numpy 数组(R_tot 应该是一个 numpy 数组)。

【问题讨论】:

  • 你可以将一个数组附加到一个数组数组中,这有什么问题?
  • @Louis 你能解释一下怎么做吗?
  • r_tot = [] 然后,当您需要添加数组r_i = [v1,v2,v3,v4,v5,v6] 时,请使用r_tot.append(r_i)。这为您提供了一个数组数组。
  • @Louis 我正在使用 Spyder,我不知道这是否是问题所在,但使用您的代码我只得到一个数组,而不是数组数组。我得到一个“数字列表”。这使用 Spyder 中的变量资源管理器。如果我打印 r_tot 我得到一个列表而不是矩阵。我需要得到一个具有组织值的矩阵以进行进一步的操作。
  • @Louse 我再次编写了代码,现在它可以使用您的建议,我不得不使用 r_tot.append(r_i)。 r_tot 不是一个 numpy 数组,如果有一个方法来使用数组做同样的事情会很好。

标签: python numpy matrix append


【解决方案1】:

您可以按照我在评论中的说明正常生成数组:

r_tot = []

for r_i in however_many_rs_there_are: # each r_i contains an array of 6 values
    r_tot.append(r_i)

然后您可以将 r_tot 转换为 numpy 数组,如下所示:

import numpy
np_array = numpy.array(r_tot)

这是一个非常简单的概念证明:

>>> import random, numpy
>>> r_tot = []
>>> for i in range(0,random.randint(1,20)): # append an arbitrary number of arrays
        r_i = [1,2,3,4,5,6]                 # all of size six
        r_tot.append(r_i)                   # to r_tot

>>> np_array = numpy.array(r_tot)           # then convert to numpy array!
>>> np_array                                # did it work?
array([[1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6],                  # yeaaaah
       [1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6],
       [1, 2, 3, 4, 5, 6]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    相关资源
    最近更新 更多