繁体   English   中英

从数组中选择非等随机整数(python)

[英]choosing non-equal random integers from an array (python)

我是python的新手。 我需要在1到100之间拉出5个随机数。但是,这五个数字不能相同。 我正在考虑创建一个向量(范围(1,101))并从向量中提取随机值,然后创建一个循环,表明如果第二个绘制等于第一个绘制,则绘制另一个随机数,如果之后的绘制等于前两次绘制等等,直到拉出5个不等的随机数。 有没有更优雅的方式来做到这一点?

使用random.sample

>>> from random import sample
>>> sample(range(1, 101), 5)
[86, 90, 20, 72, 49]

你想要的是Fisher-Yates shuffle的一个变种。 我不'做'python(我喜欢的是一个Java人),但是,它很简单......

以有序的方式创建源'set'(数组从1到101)的数组。

然后你要做的是在array.size - 1 last设置一个变量,并执行以下操作:

int[] ret = new int[5] // return array of 5 members.
for (int i = 0; i < 5; i++) { // 5 is the number of values you want.
    int rand = random(last + 1) // get a random integer from 0 to last (includes last)
    # put the value at array[rand] in your return array var
    ret[i] = array[rand]
    # move the value at the end to the value we just copied out:
    array[rand] = array[last]
    # decrease the size of the values we can select from:
    last--;
}

这样您就可以从集合中选择5个随机值。 没有重复,都具有相同的概率。

完整的Fisher-yates shuffle可以在整个阵列中就地执行此操作。 我只是使用你需要的算法的一部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM