我有一個腳本,它生成一個 0,60 之間的亂數字串列,并按升序排序。
本質上,我想檢查每個元素和它旁邊的元素之間的差異是否大于 3,如果不是,我希望重新生成串列,直到條件適用。
例如:
my_list = [1, 2, 3, 4, 5]
# this would not pass
my_list = [1, 5, 9, 13, 20]
# this would pass as the difference between each element and the next is more than 3
到目前為止我的代碼:
def generateList():
timeSlots = list(range(0, 60)) # generate random list
random.shuffle(timeSlots) # shuffle list
timeSlots = timeSlots[:9] # shorten list to 9 elements
timeSlots.sort() # sort list in ascending order
for cur, nxt in zip(timeSlots, timeSlots[1:]):
diff = (nxt - cur) # check difference
if diff < 3:
# HELP HERE
# regenerate timeSlots until the sum of each element and the next element is bigger than 3
return timeSlots
uj5u.com熱心網友回復:
你想使用all():
def generateList():
while True:
timeSlots = list(range(0, 60)) # generate random list
random.shuffle(timeSlots) # shuffle list
timeSlots = timeSlots[:9] # shorten list to 9 elements
timeSlots.sort() # sort list in ascending order
if all(nxt - cur > 3 for cur, nxt in zip(timeSlots, timeSlots[1:])):
return timeSlots
請注意,如果您只想選擇 9 個元素,則可以使用randome.sample().
import random
def generate_list():
while True:
time_slots = random.sample(range(60), 9) # note this will not include 60 in the population
time_slots.sort() # sort list in ascending order
# or combine the above 2 lines as
# time_slots = sorted(random.sample(range(60), 9))
if all(nxt - cur > 3 for cur, nxt in zip(time_slots, time_slots[1:])):
return time_slots
uj5u.com熱心網友回復:
如果您的串列不符合您的條件,您可以只執行遞回呼叫。這將在您的程式中添加一行:
import random
def generateList():
timeSlots = list(range(0, 60))
random.shuffle(timeSlots)
timeSlots = timeSlots[:9]
timeSlots.sort()
for cur, nxt in zip(timeSlots, timeSlots[1:]):
diff = (nxt - cur)
if diff < 3:
return generateList() # does not work => try a new one
return timeSlots
generateList()
uj5u.com熱心網友回復:
import random
def generateList():
while True:
timeSlots = list(range(0, 60)) # generate random list
random.shuffle(timeSlots) # shuffle list
timeSlots = timeSlots[:9] # shorten list to 9 elements
timeSlots.sort() # sort list in ascending order
for cur, nxt in zip(timeSlots, timeSlots[1:]):
diff = (nxt - cur) # check difference
if diff < 3:
break
else:
return timeSlots
print(generateList())
uj5u.com熱心網友回復:
我想檢查每個元素和它旁邊的元素之間的差異是否在 3 以上,如果不是,我希望重新生成串列,直到條件適用。
答案已經顯示了如何檢查串列,但根據您的數字,生成此類有效串列的機會可能非常低,或者根本沒有有效串列。在這種情況下,您的回圈將運行很長時間或無限期。
相反,您可以只生成一個有效串列。假設K=10元素必須小于N=60差異大于M=3。然后你知道M*(K-1)必須為間隙“保留”,你可以random.sample從其余的數字中計算出來,然后應用累積的間隙。
import random
N, M, K = 60, 3, 10
nums = sorted(random.sample(range(N - (K-1)*M), K))
# [2, 5, 13, 16, 21, 23, 27, 28, 31, 32] (random)
res = [x i*M for i, x in enumerate(nums)]
# [2, 8, 19, 25, 33, 38, 45, 49, 55, 59] (random)
作為副作用,如果沒有這樣的串列,這將立即引發例外。
因此,您的generateList函式可能如下所示,沒有回圈:
def generateList(n=60, m=3, k=10):
nums = sorted(random.sample(range(n - (k-1)*m), k))
return [x i*m for i, x in enumerate(nums)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312880.html
