0

I have a list of numbers and I would like to select n values evenly distributed across the list.

For example:

vals = list(range(10))
select_n(vals, 4)
select_n(vals, 5)

should give

[0, 3, 6, 9]
[0, 2, 5, 7, 9]

My current hack is to iterate as such:

[vals[round((len(vals) - 1)/(n-1) * i)] for i in range(n)]

Is there a Python or NumPy function to do this? If not, is there a more efficient way to write this?

Jonathon Vandezande
  • 2,446
  • 3
  • 22
  • 31

2 Answers2

1

you could use np.linspace for the "heavy" lifting:

from operator import itemgetter

a = [*range(10)]

N = 5

# if tuple ok 
itemgetter(*np.linspace(0.5,len(a)-0.5,N,dtype=int))(a)
# (0, 2, 5, 7, 9)

# if must be list
[a[i] for i in np.linspace(0.5,len(a)-0.5,N,dtype=int)]
# [0, 2, 5, 7, 9]
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
0

You can do something like this:

def select_n(vals,cnt):
    inc = int(len(vals)/cnt)
    # print(inc)
    res = [vals[i] for i in range(0,len(vals),inc)]
    # print(res)
    return res

vals = list(range(10))
# print(vals)
res = select_n(vals,4)
print(res)
arajshree
  • 626
  • 4
  • 13