从数组中选择不相等的随机整数(python)
我对python非常陌生。我需要从1到100之间抽取5个随机数。但是,这五个数字不能相同。我在考虑创建一个向量范围1101,然后从向量中提取随机值,然后创建一个循环,说明如果第二次抽取与第一次抽取相等,然后再抽取另一个随机数,如果第二次抽取与前两次抽取相等,等等,直到抽取5个不相等的随机数。有更优雅的方法吗?使用random.sample:从数组中选择不相等的随机整数(python),python,arrays,loops,random,random-sample,Python,Arrays,Loops,Random,Random Sample,我对python非常陌生。我需要从1到100之间抽取5个随机数。但是,这五个数字不能相同。我在考虑创建一个向量范围1101,然后从向量中提取随机值,然后创建一个循环,说明如果第二次抽取与第一次抽取相等,然后再抽取另一个随机数,如果第二次抽取与前两次抽取相等,等等,直到抽取5个不相等的随机数。有更优雅的方法吗?使用random.sample: 你想要的是一个变化的基础上。我不“做”python,我是一个喜欢Java的人,但是,这很简单 创建源的数组,按顺序将数组从1“设置”到101 然后,将变量l
你想要的是一个变化的基础上。我不“做”python,我是一个喜欢Java的人,但是,这很简单 创建源的数组,按顺序将数组从1“设置”到101 然后,将变量last设置为array.size-1,并执行以下操作:
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个随机值。没有重复,所有的概率都一样
一次完整的费舍尔·耶茨洗牌可以在原地完成整个阵型的洗牌。我只是使用了您需要的算法的一部分。random.samplerange1、101、5同样,在python中,这叫做列表。这永远不会选择两个相同的整数吗?例:[86,90,20,86,49]?@user3000626:读文件!如果输入没有重复项,则输出中也不会有重复项。
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--;
}