簡體   English   中英

如何從python中的給定范圍生成隨機唯一的兩個數字集

[英]How to generate random unique sets of two numbers from a given range in python

我想從要在循環中應用的給定范圍生成 x 和 y 的隨機數字集。

我嘗試了以下代碼,但如果“n”很小或循環多次,它有時會返回重復值。

    x = random.randint(0,n-1)
    y = random.randint(0,n-1)

您可以將生成的 x 和 y 存儲在列表中。 通過這種方式,您可以檢查 x 和 y 是否已經存在,如果不存在,則添加新的。

l = []
n = 1
while len(l) < 101:
    if not l:
       x = random.randint(0,n-1)
       y = random.randint(0,n-1)
       l.append((x, y))
    else:
       x = random.randint(0,n-1)
       y = random.randint(0,n-1)
       if (x, y) not in l:
           l.append((x, y))
    n += 1

這將在每次循環時為您提供一個唯一的元組(x, y)

以下應該工作:

from random import choice
x = random.randint(0,n-1)
y=  choice([i for i in range(0,n-1) if i!=x])

思考了一會兒,我想出了以下代碼:

n = 5
k = 25
List = random.sample(range(n*n),k)
for i in range(k):
    a = List[i] // n
    b = List[i] % n
    List[i] = (a, b)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM