从列表中生成一个随机数,不包括其中一个数字

2024-05-23 19:44:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个从0到n的连续整数列表,然后从该列表中选取一个randon整数,然后从同一个列表中生成另一个随机整数,其中不包括先前生成的整数。你知道吗

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))

我知道这行不通,因为我的for循环很不确定。我已经很长时间没有使用python了,而且我刚刚开始一个项目,让自己重新投入到这个项目中去是有点棘手的!你知道吗


Tags: 项目creating列表formynp整数random
3条回答

另一个答案是:

1)生成初始列表。你知道吗

2)洗牌列表。如果没有库函数来执行此操作,则使用Fisher-Yates shuffle。提示:这里可以节省很多时间。你知道吗

3)从无序排列的列表中选择第一个数字。这是你的初始号码。你知道吗

4)从无序排列的列表中选择第二个数字。这是你的第二个数字,几乎是随机的,与第一个数字不一样。你知道吗

我想你要做的是随机抽样,不需要更换。你知道吗

假设您要选择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)

Help on method sample in module random:

sample(self, population, k) method of random.Random instance

Chooses k unique random elements from a population sequence.

Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.

To choose a sample in a range of integers, use xrange as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(xrange(10000000), 60)

然后,要在范围[0, n]内选取k随机的非重复数,可以执行以下操作:

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

相关问题 更多 >