根据起始数组的特定区域将Numpy数组的元素保存到不同的Numpy数组中(Python)



我想根据我从第一个数组定义的区域将一个numpy数组的元素保存到不同的numpy数组

length_of_start_array = 42 // this number can change i loop over diffrent arrays 
start_indices_of_areas = [2, 5, 6]
length_of_areas = [2, 3, 1, 36]

所以我想做的是,我循环这个数组,例如有42个元素,它保存第一个数组中的元素,它的元素来自(0-2)然后我想要第二个数组,它保存(3-5)然后从(5-6)然后form (6-42)所以我的理解是,我需要两个循环?一个指定了我想要循环的区域另一个是循环该区域的长度。我试过了,但是失败了

for area in range(0, len(length_of_areas)):
for element in range(0, length_of_areas[area]):
//further code

这是一个部分解决方案-还可能有其他更优雅的解决方案(例如使用列表推导式)

当你有索引时,你不需要数组长度。我把清单打印出来,而不是列清单,所以你应该改变这个。

import random
length_of_start_array = 20 # this number can change i loop over diffrent arrays 
randomlist = random.sample(range(1, 100), length_of_start_array)
start_indices_of_areas = [0, 2, 5, 6]
#length_of_areas = [2, 3, 1, 36]
print(randomlist)
for i, index in enumerate(start_indices_of_areas):
if i==len(start_indices_of_areas)-1:
splitArray=randomlist[index:]
else: 
length=start_indices_of_areas[i+1]-start_indices_of_areas[i]
splitArray=randomlist[index:index+length]
print(splitArray)

最新更新