Select N evenly spaced out elements in array, including first and last

前端 未结 3 1746
无人及你
无人及你 2021-01-01 20:34

I have an array of arbitrary length, and I want to select N elements of it, evenly spaced out (approximately, as N may be even, array length may be prime, etc) that includes

3条回答
  •  伪装坚强ぢ
    2021-01-01 21:28

    Your GetSpacedElements() function should also take in the array to avoid unfortunate side effects elsewhere in code. That said, the function would need to look like this:

    import numpy as np
    
    def GetSpacedElements(array, numElems = 4):
        out = array[np.round(np.linspace(0, len(array)-1, numElems)).astype(int)]
        return out
    
    arr = np.arange(17)
    print(array)
    spacedArray = GetSpacedElements(arr, 4)
    print (spacedArray)
    

提交回复
热议问题