简体   繁体   English

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

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

I'm very new to python. 我是python的新手。 I need to pull 5 random numbers between 1 and 100. However, these five numbers cannot be the same. 我需要在1到100之间拉出5个随机数。但是,这五个数字不能相同。 I was thinking about creating a vector (range (1, 101)) and pulling random values from the vector, and then creating an loop that says if the second draw is equal to the first then draw another random number and if the draw after that is equal to the previous two draw again, etc. until 5 non-equal random numbers are pulled. 我正在考虑创建一个向量(范围(1,101))并从向量中提取随机值,然后创建一个循环,表明如果第二个绘制等于第一个绘制,则绘制另一个随机数,如果之后的绘制等于前两次绘制等等,直到拉出5个不等的随机数。 Is there a more elegant way to do this? 有没有更优雅的方式来做到这一点?

Use random.sample : 使用random.sample

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

What you want is a variation on the Fisher-Yates shuffle . 你想要的是Fisher-Yates shuffle的一个变种。 I don't 'do' python (I'm a Java person by preference), but, it's quite simple.... 我不'做'python(我喜欢的是一个Java人),但是,它很简单......

create an array of your source 'set' (the array from 1 to 101), in an ordered fashion. 以有序的方式创建源'set'(数组从1到101)的数组。

Then what you do is set a variable last to the array.size - 1 , and do the following: 然后你要做的是在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--;
}

This way you get to select 5 random values from your set. 这样您就可以从集合中选择5个随机值。 No duplcicates, all with the same probability. 没有重复,都具有相同的概率。

A full Fisher-yates shuffle can do this for the entire array, in-place. 完整的Fisher-yates shuffle可以在整个阵列中就地执行此操作。 I am just using a part of the algorithm that you need. 我只是使用你需要的算法的一部分。

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

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