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

Save elements of Numpy array into different numpy arrays dependent on specific area of start array (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)然后形成(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)