[英]How to generate random pairs of numbers in Python, including pairs with one entry being the same and excluding pairs with both entries being the same?
[英]How to generate pairs of random numbers that first number is smaller than second one
我想生成第一個數字小於第二個數字的隨機數對,例如[[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)
到目前為止,似乎大多數解決方案都沒有考慮到兩個獨立生成的隨機數可能相等。 (哪個 OP 聲明他不想要)。
我認為sample
更好。
from random import sample
sorted(sample(range(1,10),2))
這保證了 2 個按遞增順序的唯一數字。
一種方法世界是對生成的隨機數進行排序
sorted([randint(1, 10), randint(1, 10)]) # [3, 7], [4, 6], [1, 10]
好吧,由於數字只是隨機的,您可以簡單地將以下內容添加到您的代碼中:
和你一樣:
a = random.randint(1, 10)
b = np.random.randint(1, 10, (a, 2))
然后:
b = [sorted(pair) for pair in b]
生成兩個整數並排序:
sorted(np.random.randint(0,100,2))
[28, 94]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.