NumPy - 选择范围内唯一整数的随机列表

Jiv*_*van 0 python numpy

n = range(1, n+1)我有随机生成的列表n * p唯一整数.

例如,如果n = 10p = 0.3随后可能的结果可能是:

[2, 6, 9]
[1, 5, 7]
[3, 4, 8]
[3, 5, 6]
etc
Run Code Online (Sandbox Code Playgroud)

以下Python代码完美地完成了这项工作:

import random

n = 250000
p = 0.8
np = int(n * p)

result = []
for i in range(np):
    attempt = random.randint(1, n)
    if attempt not in result:
        result.append(attempt)
Run Code Online (Sandbox Code Playgroud)

但是,因为它是Python,它可能需要很长时间(比如超过一分钟)np > 200000.

你能看到更有效的上述解决方案NumPy吗?

qua*_*ind 6

试试这个:

result = random.sample(range(1,n+1),p*n)
Run Code Online (Sandbox Code Playgroud)

链接到的文档random.sample