所以..我正在處理這個回圈:
stuff_so_far = [intl_pt]
for i in range(0, num_pts - 1):
rdm = random.randint(0, len(points_in_code) - 1)
a = (stuff_so_far[i][0] points_in_code[rdm][0]) // 2
b = (stuff_so_far[i][1] points_in_code[rdm][1]) // 2
stuff_so_far.append((a, b))
基本上我想要實作的是每次代碼回圈時為“points_in_code”獲取一個隨機索引。它現在正在這樣做,但我想知道的是,我如何讓它不隨機重復一個數字?如,如果在回圈的第一次迭代中,rdm 被設定為 1,然后在回圈的第二次迭代中,rdm 被設定為 3,并且在某些情況下,rdm 可以在第三次迭代中再次設定為 1。我如何使它不再為 1 (只要回圈仍在進行)?
我已經嘗試了我所知道的一切并在網上搜索但我什么也沒找到,我如何在不過多更改代碼的情況下實作這一點?(我是編程新手)我知道每次呼叫 random.randint() 時,我都會創建一個亂數,它不會神奇地更改為每次回圈迭代時在數字之前未使用的新亂數。
uj5u.com熱心網友回復:
您可以使用random.sample:
import random
points_in_code = [11, 4, 13, 18, 7, 12] # Just a example
num_pts = 4
indexes = random.sample(range(len(points_in_code)), num_pts - 1)
for rdm, i in zip(indexes, range(0, num_pts - 1)):
pass # rdm will be a random unique index
# i will increase 1 each iteration
您也可以使用enumerate(indexes)而不是,zip(indexes, range(0, num_pts - 1))但是您需要反轉iand rdm。
有關更多資訊,請參閱random.sample 的檔案。另請參閱有關zip和列舉的資訊
uj5u.com熱心網友回復:
您可以使用陣列來跟蹤您已經使用的亂數。如果你得到一個你已經擁有的亂數,你只需要重新生成一個。
stuff_so_far = [intl_pt]
tracking_num = [] # keeps track of the random number that was alreadey used.
for i in range(num_pts - 1): # small tip you can create a for-loop without the zero in the beginning.
# while loop in which a number will be regenerated if the current random number
# is contained in the 'tracking_num' array.
rdm = random.randint(0, len(points_in_code) - 1)
while tracking_num.__contains__(rdm):
rdm = random.randint(0, len(points_in_code) - 1)
a = (stuff_so_far[i][0] points_in_code[rdm][0]) // 2
b = (stuff_so_far[i][1] points_in_code[rdm][1]) // 2
stuff_so_far.append((a, b))
uj5u.com熱心網友回復:
嘗試以下方法
import random as rnd
## Lets say you want at max 100
MAX=100
arr = [i for i in range(101)]
while True:
curr = rnd.choice(arr)
arr.remove(curr)
print(curr)
if len(arr)==0: break
你的代碼:
stuff_so_far = [intl_pt]
choice_arr = [i for i in range(len(points_in_code))]
for i in range(0, num_pts - 1):
rdm = random.choice(choice_arr)
choice_arr.remove(rdm)
if len(choice_arr)==0:
print("No more choices available")
break
a = (stuff_so_far[i][0] points_in_code[rdm][0]) // 2
b = (stuff_so_far[i][1] points_in_code[rdm][1]) // 2
stuff_so_far.append((a, b))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/525169.html
下一篇:如何對3d陣列中的每個陣列求和
