Python中的数组组织

2024-04-19 06:53:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的python代码:

ht_24 = []
ht_23 = []
ht_22 = []
...

all_arr = [ht_24, ht_23, ht_22, ht_21, ht_20, ht_19, ht_18, ht_17, ht_16, ht_15, ht_14, ht_13, ht_12, ht_11, ht_10, ht_09, ht_08, ht_07, ht_06, ht_05, ht_04, ht_03, ht_02, ht_01]    

i = 0                                         
j = 0                                         
while i < 24:                                 
    while j < 24864:                          
        all_arr[i].append(read_matrix[j+i])   
        j += 24                               
        print(j)                              
    i += 1                                    
    print(i)

其中read\u矩阵是一个形状为24864,17的数组。你知道吗

我想从不同的起始索引(0-24)中读取每24行,并将它们附加到每行对应的数组中。请帮帮我,这太难了!你知道吗


Tags: 代码read矩阵数组allmatrixht形状
3条回答

numpy库能做你想做的吗?你知道吗

import numpy as np
# 24864 row, 17 columns
read_matrix = np.arange(24864*17).reshape(24864,17)
new_matrices = [[] for i in range(24)] 

for i in range(24):
    # a has 17 columns
    a = read_matrix[slice(i,None,24)]
    new_matrices[i].append(a)

你的问题有点不清楚,但我认为

list(zip(*zip(*[iter(read_matrix)]*24)))

可能就是你要找的。你知道吗

list(zip(*zip(*[iter(range(24864))]*24)))[0][:5]

上面只看索引,第一个子列表的前几个元素是

(0, 24, 48, 72, 96)

在Python中要学习两件事:

第一:对于循环,当你提前知道你要经历多少次循环时。上面的while循环都是这种类型。请尝试以下方法:

for i in range(24):
    for j in range(0, 24864, 24):
        all_arr[i].append(read_matrix[j+i])
        print(j)
    print(i)

最好让语言为您处理索引值。你知道吗

两个:列表理解:在列表结构中有一个循环。您发布的整个代码可以转换为一条语句:

all_arr = [[read_matrix[j+i] \
                for j in range(0, 24864, 24) ] \
            for i in range(24) ]

相关问题 更多 >