【问题标题】:Save elements of Numpy array into different numpy arrays dependent on specific area of start array (Python)根据起始数组的特定区域(Python)将 Numpy 数组的元素保存到不同的 numpy 数组中
【发布时间】:2021-01-24 08:02:12
【问题描述】:

我想将一个 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

【问题讨论】:

    标签: python numpy loops area


    【解决方案1】:

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

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-12-25
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 2019-02-17
      • 1970-01-01
      • 2011-05-12
      相关资源
      最近更新 更多