Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python (几乎)从列表中均匀地选择项目_Python_List_Math_Random_Permutation - Fatal编程技术网

Python (几乎)从列表中均匀地选择项目

Python (几乎)从列表中均匀地选择项目,python,list,math,random,permutation,Python,List,Math,Random,Permutation,我有一个N元素的列表,我想对M进行采样(查看一些测试的结果(甚至包括上面包含的测试),问题是当M>N/2时。也就是说,当超过一半的值被采样时。但它对MN/2时反转问题: 注意:这实际上是在为M元素创建一个大小为N的屏蔽列表,该列表的大小为False 如果存在更优雅的解决方案,我仍然会感兴趣。对于一种快速但看似随机的方法,请看一看@PrestonHager,这很有趣,但您认为它在这里有什么用处?我想提出同样的建议。 q, r = divmod(N, M) indices = [q*jj + min

我有一个
N
元素的列表,我想对
M进行采样(查看一些测试的结果(甚至包括上面包含的测试),问题是当
M>N/2
时。也就是说,当超过一半的值被采样时。但它对
M
非常有效。因此,我目前使用的解决方案只是在
M>N/2
时反转问题:

注意:这实际上是在为
M
元素创建一个大小为
N
的屏蔽列表,该列表的大小为False


如果存在更优雅的解决方案,我仍然会感兴趣。

对于一种快速但看似随机的方法,请看一看@PrestonHager,这很有趣,但您认为它在这里有什么用处?我想提出同样的建议。
q, r = divmod(N, M)
indices = [q*jj + min(jj, r) for jj in range(M)]
N=11 M=6
good_index = [0 1 0 1 0 1 0 1 0 1 0]

N=14 M=6
good_index = [0 1 1 0 1 1 0 1 0 1 0 1 0 1]
N=16 M=10
bad_index = [0 1 0 1 0 1 0 1 0 1 0 1 0 0 0 0]

N=14 M=10
bad_index = [0 1 0 1 0 1 0 1 0 0 0 0 0 0]
step = int(floor(N/M))
last = M * step  # this prevents us from getting M+1 elements
indices = [ii for ii in range(0, last, step)]
import numpy as np

def even_select(N, M):
    if M > N/2:
        cut = np.zeros(N, dtype=int)
        q, r = divmod(N, N-M)
        indices = [q*i + min(i, r) for i in range(N-M)]
        cut[indices] = True
    else:
        cut = np.ones(N, dtype=int)
        q, r = divmod(N, M)
        indices = [q*i + min(i, r) for i in range(M)]
        cut[indices] = False

    return cut