我有一个数字列表,我想选择均匀分布在列表中的n个值。
例如:
vals = list(range(10))
select_n(vals, 4)
select_n(vals, 5)
应该给予
[0, 3, 6, 9]
[0, 2, 5, 7, 9]
我当前的hack是这样迭代:
[vals[round((len(vals) - 1)/(n-1) * i)] for i in range(n)]
是否有Python或NumPy函数可以做到这一点?如果没有,有没有更有效的方式编写此代码?
答案 0 :(得分:1)
您可以使用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]
答案 1 :(得分:0)
您可以执行以下操作:
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)