Splitting a list into N parts of approximately equal length

前端 未结 30 1743
迷失自我
迷失自我 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:05

    Implementation using numpy.linspace method.

    Just specify the number of parts you want the array to be divided in to.The divisions will be of nearly equal size.

    Example :

    import numpy as np   
    a=np.arange(10)
    print "Input array:",a 
    parts=3
    i=np.linspace(np.min(a),np.max(a)+1,parts+1)
    i=np.array(i,dtype='uint16') # Indices should be floats
    split_arr=[]
    for ind in range(i.size-1):
        split_arr.append(a[i[ind]:i[ind+1]]
    print "Array split in to %d parts : "%(parts),split_arr
    

    Gives :

    Input array: [0 1 2 3 4 5 6 7 8 9]
    Array split in to 3 parts :  [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8, 9])]
    

提交回复
热议问题