【问题标题】:How to cast a list into an array with specific ordering of the elements in the array如何将列表转换为具有数组中元素特定顺序的数组
【发布时间】:2020-03-06 08:30:33
【问题描述】:

如果我有一个清单:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]

我想将上面的列表转换成具有以下元素排列的数组:

array([[ 1,  2,  3,  7,  8,  9]
       [ 4,  5,  6, 10, 11, 12]
       [13, 14, 15, 19, 20, 21]
       [16, 17, 18, 22, 23, 24]])

我该怎么做或者最好的方法是什么?非常感谢。

我在下面以粗略的方式完成了此操作,我将获取所有子矩阵,然后在最后连接所有子矩阵:

np.array(results[arr.shape[0]*arr.shape[1]*0:arr.shape[0]*arr.shape[1]*1]).reshape(arr.shape[0], arr.shape[1])
array([[1, 2, 3],
       [4, 5, 6]])

np.array(results[arr.shape[0]*arr.shape[1]*1:arr.shape[0]*arr.shape[1]*2]).reshape(arr.shape[0], arr.shape[1])
array([[ 7,  8,  9],
       [ 10, 11, 12]])

etc,

但我需要一种更通用的方法来执行此操作(如果有的话),因为我需要对任何大小的数组执行此操作。

【问题讨论】:

  • 你应该展示你自己尝试过的东西。
  • 更新了我的问题,谢谢。看看能不能帮忙

标签: python arrays list reshape


【解决方案1】:

您可以使用 numpy 中的 reshape 函数,并进行一些索引:

a = np.arange(24)
>>> a
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23])

使用重塑和一些索引:

a = a.reshape((8,3))
idx = np.arange(2)
idx = np.concatenate((idx,idx+4))
idx = np.ravel([idx,idx+2],'F')
b = a[idx,:].reshape((4,6))

输出

>>> b
array([[ 0,  1,  2,  6,  7,  8],
       [ 3,  4,  5,  9, 10, 11],
       [12, 13, 14, 18, 19, 20],
       [15, 16, 17, 21, 22, 23]])

这里传递给 reshape 的元组 (4,6) 表示您希望数组是二维的,并且有 4 个 6 个元素的数组。可以计算这些值。 然后我们计算索引来设置数据的正确顺序。显然,这有点复杂。由于我不确定您所说的“任何大小的数据”是什么意思,因此我很难为您提供一种不可知的方法来计算该索引。

显然,如果您使用的是列表而不是 np.array,则可能必须先转换列表,例如使用 np.array(your_list)

编辑

我不确定这是否正是您所追求的,但这应该适用于任何可被 6 整除的数组:

def custom_order(size):
    a = np.arange(size)
    a = a.reshape((size//3,3))
    idx = np.arange(2)
    idx = np.concatenate([idx+4*i for i in range(0,size//(6*2))])
    idx = np.ravel([idx,idx+2],'F')
    b = a[idx,:].reshape((size//6,6))
    return b
>>> custom_order(48)
array([[ 0,  1,  2,  6,  7,  8],
       [ 3,  4,  5,  9, 10, 11],
       [12, 13, 14, 18, 19, 20],
       [15, 16, 17, 21, 22, 23],
       [24, 25, 26, 30, 31, 32],
       [27, 28, 29, 33, 34, 35],
       [36, 37, 38, 42, 43, 44],
       [39, 40, 41, 45, 46, 47]])

【讨论】:

  • 谢谢,但是如果我使用 reshape() ,则条目的最终排列不是我所追求的。如果你看我的数组,4、5、6 低于 1、2、3 等。
  • 太好了!我现在明白了主要的想法,这都是关于重新排列索引的。非常感谢冠军!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-02
  • 1970-01-01
  • 2014-07-29
  • 2016-02-12
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
相关资源
最近更新 更多