我有一个脚本,它生成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发布于 2021-10-05 13:03:35
你想要使用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发布于 2021-10-05 13:32:24
我希望检查每个元素与其旁边的元素之间的差异是否高于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)]发布于 2021-10-05 15:12:27
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())https://stackoverflow.com/questions/69450910
复制相似问题