【问题标题】:How to create a list made out of matrices in python?如何在python中创建由矩阵组成的列表?
【发布时间】:2021-06-13 05:38:05
【问题描述】:

我在下面的列表中填满了矩阵:

incSplitList = [numpy.zeros((4, 4))] * nmbDurations

在我开始使用列表之前看起来像这样:

incSplit = numpy.zeros((4, 4)) 
incSplit2 = numpy.zeros((4, 4))
incSplit3 = numpy.zeros((4, 4))
incSplit4 = numpy.zeros((4, 4))
incSplit5 = numpy.zeros((4, 4))

现在我需要使用 incSplitList 对以下代码进行压缩和 Python 化:

tmpValue += incSplit[x][y] 
tmpValue2 += incSplit2[x][y]
tmpValue3 += incSplit3[x][y]
tmpValue4 += incSplit4[x][y]
tmpValue5 += incSplit4[x][y]

我也在使用新的 tmpValueList:

tmpValueList = [0] * nmbDurations

但是我很困惑如何遍历 incSplitList,同时还访问矩阵中的元素 x 和 y,如上面的代码: 所以是的,长话短说: 下面的代码如何使用列表 incSplitList 和 tmpValueList 进行压缩?

tmpValue += incSplit[x][y] 
tmpValue2 += incSplit2[x][y]
tmpValue3 += incSplit3[x][y]
tmpValue4 += incSplit4[x][y]
tmpValue5 += incSplit4[x][y]

【问题讨论】:

  • incSplitList created with a list * 是一个只有一个数组的列表,但对它有多个引用。使用* 创建列表很棘手,而且经常会产生意想不到的结果。
  • 索引二维数组最好使用incSplit[x,y][x][y] 方法(有时)有效,但更典型的是列表索引。如果您创建了arr=np.zeros((5,4,4)),您可以跳过所有这些临时名称和迭代。
  • 看来你只是想sum(incSplitList)...

标签: python list numpy matrix


【解决方案1】:

制作数组列表

In [56]: alist = [np.arange(2*i,2*i+3) for i in range(3)]
In [57]: alist
Out[57]: [array([0, 1, 2]), array([2, 3, 4]), array([4, 5, 6])]

由于它们的大小都相同,我们可以从列表中创建一个数组:

In [58]: arr = np.array(alist)
In [59]: arr
Out[59]: 
array([[0, 1, 2],
       [2, 3, 4],
       [4, 5, 6]])

访问元素:

In [60]: alist[2][1]
Out[60]: 5
In [61]: arr[2,1]
Out[61]: 5

对“行”求和:

In [62]: [sum(l) for l in alist]
Out[62]: [3, 9, 15]

但是使用数组我们可以对列或行求和:

In [63]: arr.sum(axis=0)
Out[63]: array([ 6,  9, 12])
In [64]: arr.sum(axis=1)
Out[64]: array([ 3,  9, 15])

不要使用* 来“复制”列表,除非您知道自己在做什么,而且这是故意的。

In [65]: blist = [np.zeros((2,2),int)]*3
In [66]: blist
Out[66]: 
[array([[0, 0],
        [0, 0]]),
 array([[0, 0],
        [0, 0]]),
 array([[0, 0],
        [0, 0]])]
In [67]: blist[1][1,:] = 3      # change one row of one element the list
In [68]: blist
Out[68]: 
[array([[0, 0],
        [3, 3]]),
 array([[0, 0],
        [3, 3]]),
 array([[0, 0],
        [3, 3]])]

查看所有更改。

【讨论】:

  • 感谢您抽出宝贵时间回答,但我真的不明白您给我的答案。进出是什么意思? 56 - 68 的数字是多少
  • In/Out` 是我运行此代码的 ipython 会话中的行号。除了作为参考,这些数字并不重要。不幸的是,很难说你对基本的 Python 编码了解多少(或者最重要的是numpy)。
  • 是否也可以只使用for j in range(nmbDurations): tmpValueList[j] += incSplitList[j][x][y]
猜你喜欢
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
  • 2012-11-25
  • 2015-07-12
  • 2016-07-29
  • 1970-01-01
  • 2021-12-29
相关资源
最近更新 更多