我有一个数字列表,我想选择在列表中均匀分布的n个值。
例如:
vals = list(range(10))
select_n(vals, 4)
select_n(vals, 5)应该给予
[0, 3, 6, 9]
[0, 2, 5, 7, 9]我现在的想法是这样迭代:
[vals[round((len(vals) - 1)/(n-1) * i)] for i in range(n)]有没有Python或NumPy函数可以做到这一点?如果没有,有没有更有效的方法来写这个?
发布于 2019-06-20 06:50:49
你可以使用np.linspace来完成“繁重的”任务:
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]发布于 2019-06-20 05:59:25
你可以这样做:
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)https://stackoverflow.com/questions/56676387
复制相似问题