如何生成不同的随机数? [英] How to generate random numbers that are different?

查看:150
本文介绍了如何生成不同的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
随机选择N个项目

Possible Duplicate:
pick N items at random

我需要生成1到49之间的6个随机数,但是它们不能相同.我知道如何使它们随机化,但我不确定如何确保它们不同.

I need to generate 6 random numbers between 1 and 49, but they cannot be the same. I know how to do make them random, I just am not sure how to ensure that they are different.

工作表建议显示每个数字并将其设置为零,但我看不出有什么帮助.

The worksheet recommends displaying each number and setting it to zero, but I don't see how that would help.

任何建议都将不胜感激.

Any advice is greatly appreciated.

推荐答案

您可以使用

You can use random.sample:

>>> random.sample(xrange(1,50), 6)
[26, 39, 36, 46, 37, 1]


工作表建议显示每个数字并将其设置为零,但我看不出有什么帮助."

假设这是一项任务,并且您需要自己实施抽样,则可以

Assuming this is an assignment and you need to implement the sampling yourself, you could take a look at how random.sample is implemented. It's really informative, but may be too complicated for your needs since the code also ensures that all sub-slices will also be valid random sample. For efficiency, it also uses different approaches depending on the population size.

对于工作表,我认为它假设您从1到49的数字列表开始,并建议您将选择的数字替换为0,以便在重新选择时可以跳过.以下是一些伪代码,可以帮助您入门:

As for the worksheet, I believe it assumes you're starting off with a list of numbers from 1 to 49 and suggests that you replace numbers that you're selected with 0 so there can be skipped if reselected. Here's some pseudo code to get you started:


population = range(1, 50)  # list of numbers from 1 to 49
sample = []
until we get 6 samples:
  index = a random number from 0 to 48  # look up random.randint()
  if population[index] is not 0:  # if we found an unmarked value
    append population[index] to sample
    set population[index] = 0  # mark selected

如果您想尝试一些不同的方法,则可以考虑其他许多方法,例如将列表随机化然后截断,或者某种形式的储层采样.

If you wish to attempt something different, there are many other approaches to consider e.g. randomising the list then truncating, or some form of reservoir sampling.

祝您工作顺利.

这篇关于如何生成不同的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆