Splitting a list into N parts of approximately equal length

前端 未结 30 1345
迷失自我
迷失自我 2020-11-22 16:16

What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in o

30条回答
  •  感情败类
    2020-11-22 17:06

    1>

    import numpy as np
    
    data # your array
    
    total_length = len(data)
    separate = 10
    sub_array_size = total_length // separate
    safe_separate = sub_array_size * separate
    
    splited_lists = np.split(np.array(data[:safe_separate]), separate)
    splited_lists[separate - 1] = np.concatenate(splited_lists[separate - 1], 
    np.array(data[safe_separate:total_length]))
    
    splited_lists # your output
    

    2>

    splited_lists = np.array_split(np.array(data), separate)
    

提交回复
热议问题