Python 如何使用数组中元素的特定顺序将列表强制转换到数组中

Python 如何使用数组中元素的特定顺序将列表强制转换到数组中,python,arrays,list,reshape,Python,Arrays,List,Reshape,如果我有一份清单: 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, 2

如果我有一份清单:

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,
但我需要一种更通用的方法(如果有),因为我需要对任何大小的数组执行此操作。

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

a = np.arange(24)
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))
使用重塑和一点索引:

a = np.arange(24)
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]])
在这里,传递给整形的元组
(4,6)
表示您希望数组是二维的,并且有4个包含6个元素的数组。可以计算这些值。 然后我们计算索引以设置数据的正确顺序。显然,这有点复杂。因为我不确定你所说的“任何大小的数据”是什么意思,所以我很难给你一个不可知的方法来计算这个指数

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

编辑

我不确定这是否正是您想要的,但这应该适用于任何可被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

你应该展示你自己尝试过的。更新我的问题谢谢。你能看看你是否能帮上忙吗?谢谢,但是如果我使用整形()的话,结果的条目排列就不是我想要的了。如果你看我的数组,4,5,6低于1,2,3等等,那太棒了!我现在明白了主要的意思,就是重新安排索引。多谢冠军!