【问题标题】:I need to generate x random numbers in an interval from 1 to x but each number have to occur only once我需要在 1 到 x 的区间内生成 x 个随机数,但每个数字只能出现一次
【发布时间】:2014-10-24 16:30:54
【问题描述】:

我需要生成一个随机数,实际上我需要从 1 到 70128 的 70128 个随机数。这是我正在使用的:

index = numpy.random.randint(1,70128,70128)

另一件事是,我只需要生成 1 到 70128 之间的每个数字一次。

这意味着我需要一个 1 到 70128 之间的 70128 个随机生成数字的列表,但每个数字只能出现一次。

【问题讨论】:

  • 很高兴您发现这两个答案都有帮助!请注意,您只能选择一个对您最有帮助的,而不是两者兼而有之。哪个答案得到复选标记完全取决于您!
  • 你根本不想要随机数。您需要精确的数字 1..70128,以随机顺序。这被称为洗牌,就像人们对一副纸牌所做的那样。创建一个数组,然后使用 random.shuffle()。

标签: python random numbers generated


【解决方案1】:

您需要在1x 之间的x 随机数,它们都是唯一的,那么您只需要一个随机排列的范围

x = 70128
numbers = range(1, x + 1)
random.shuffle(numbers)

如果您使用的是 Python 3,您希望将 list() 调用添加到 range() 结果。

使用x = 10 在 Python 2.7 上演示实用性:

>>> import random
>>> x = 10
>>> numbers = range(1, x + 1)
>>> random.shuffle(numbers)
>>> numbers
[5, 2, 6, 4, 1, 9, 3, 7, 10, 8]

【讨论】:

  • 执行此操作时出现此错误 IndexError: index 70128 is out of bounds for size 70128
  • @SmailKozarcanin:Python 索引从 0 开始,因此您可以索引从 0 到 70127 的列表;最后一个索引总是len(listobj) - 1
【解决方案2】:

使用 numpy 的 random.permutation 函数,如果给定单个标量参数 x,它将返回从 0 到 x 的数字的随机排列。例如:

np.random.permutation(10)

给予:

array([3, 2, 8, 7, 0, 9, 6, 4, 5, 1])

所以,特别是,np.random.permutation(70128) + 1 完全按照您的意愿行事。

【讨论】:

  • 执行此操作时出现此错误 IndexError: index 70128 is out of bounds for size 70128
猜你喜欢
  • 2022-09-27
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
相关资源
最近更新 更多