【问题标题】:How to generate pairs of random numbers that first number is smaller than second one如何生成第一个数字小于第二个数字的随机数对
【发布时间】:2020-12-30 22:12:30
【问题描述】:

我想生成第一个数字小于第二个数字的随机数对,例如[[3 8] [2 5] [8 9] [8 10] [5 9] [3 7]]。我尝试使用以下代码,但由于随机生成的所有值,一些第一个元素大于第二个元素,其中一些相等。

a=random.randint(1, 10)
b = np.random.randint(1,10,(a,2))
print(b)

【问题讨论】:

  • 如果第一个数字更大,只需交换位置
  • @Jan 如果第一个数字是 1 或 min,这种方法将不起作用
  • 除了第二个更大之外,您根本没有说任何关于数字的内容。因此,例如,您可以在 1 到 10 之间选择第一个,在 11 到 20 之间选择第二个。这个问题需要更多细节。

标签: python arrays random


【解决方案1】:

一种方法是在生成后对随机数进行排序

sorted([randint(1, 10), randint(1, 10)])  # [3, 7], [4, 6], [1, 10]

【讨论】:

  • 这并不能保证数字不相等,这是OP的要求。
【解决方案2】:

好吧,由于数字只是随机的,您可以简单地将以下代码添加到您的代码中:

和你一样:

a = random.randint(1, 10)    
b = np.random.randint(1, 10, (a, 2))     

然后:

b = [sorted(pair) for pair in b]

【讨论】:

    【解决方案3】:

    生成两个整数并排序:

    sorted(np.random.randint(0,100,2))
    [28, 94]
    

    【讨论】:

      【解决方案4】:

      到目前为止,似乎大多数解决方案都没有考虑到两个独立生成的随机数可能相等。 (哪个 OP 声明他不想要)。

      我认为sample 更好。

      from random import sample
      sorted(sample(range(1,10),2))
      

      这保证了 2 个按递增顺序的唯一数字。

      【讨论】:

      • 当我将大小更改为 :sorted(sample(range(1,10),(a.2))) 时它不起作用,其中 a 是一个随机数。
      • 为什么是 a.2?为什么不呢?
      猜你喜欢
      • 2022-11-21
      • 2013-01-06
      • 2012-04-12
      • 2012-01-25
      • 2017-02-13
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多