Generate a random number from a list, not including one of the numbers

时间:2016-06-18 20:26:31

标签: python list random

I am trying to create a list of sequential integers from 0 to n, then after picking a randon integer from that list, generate another random integer from the same list that doesn't include the integer previously generated.

n = 10

a = np.arange(1,n) #Creating my initial list

for b=np.random.choice(a): #Generating my first random number
    c=np.random.choice(np.arange(1,b)) or np.random.choice(np.arange(b+1,n))

I know that this won't work because my for loop is pretty iffy. I haven't used python in a long time and I am just starting a project and getting myself back into it is proving to be a little tricky!

3 个答案:

答案 0 :(得分:3)

我认为您尝试执行的过程是随机抽样而无需替换。

假设你想选择k个数字:

import numpy as np
n = 10
k = 3

a = np.arange(1,n) #Creating my initial list

numbers = np.random.choice(a, k, replace=False)

答案 1 :(得分:1)

另一个答案:

1)生成您的初始列表。

2)随机播放清单。如果没有库函数,那么使用Fisher-Yates shuffle。提示:这里节省了大量时间。

3)从洗牌列表中选择第一个号码。这是您的初始号码。

4)从随机列表中选择第二个数字。这是你的第二个数字(几乎)是随机的,与第一个数字不同。

答案 2 :(得分:0)

  

随机模块中方法示例的帮助:

     

随机的样本(self,population,k)方法。随机实例

     

从群体序列中选择k个唯一的随机元素。

     

返回包含来自总体的元素的新列表,同时为   让原始人口保持不变。结果列表是
  在选择顺序中,所有子切片也将是有效的随机
  样本。这允许抽奖获奖者(样本)被分割   成为大奖和第二名的获奖者(下属)。

     

人口中的成员不需要是可以清洗或独特的。如果是   人口包含重复,然后每次出现都是可能的   选择样本。

     

要选择整数范围内的样本,请使用xrange作为参数   这对于从中采样来说尤其快速且节省空间   人口众多:样本(xrange(10000000),60)

然后在范围k中选择[0, n]个随机非重复数字,您可以这样做:

import random
result_list = random.sample(xrange(n + 1), k)