gpt4 book ai didi

python - 如何将列表转换为具有数组中元素特定顺序的数组

转载 作者:行者123 更新时间:2023-12-04 10:27:46 28 4
gpt4 key购买 nike

如果我有一个 list :

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,

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

最佳答案

您可以使用 reshape来自 numpy 的函数,带有一些索引:

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])

使用 reshape 和一些索引:
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)传递给 reshape 表示您希望您的数组是二维的,并且有 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]])

关于python - 如何将列表转换为具有数组中元素特定顺序的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60560192/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com