2 回答
TA贡献1824条经验 获得超5个赞
首先,让我们确保我理解您要执行的操作:“我正在尝试创建一个具有唯一随机值的列表,这些随机值至少成对地相差一个给定的因子,并且都以两个值为界。” “我试图让所有值都在 10 到 502 之间,而列表中的所有值至少相隔 64 个单位或更多。”
然后,按照您的使用方法random.randint:
import random # to generate random values
randVals = [] # and keep those values in a list
factor = 64 # values should differ by this factor
low = 10 # lower bound
high = 502 # upper bound
x = low # start at lower bound
length = 8 # list should be of this length
if(high - factor*length)<low:
print('Impossible to generate list with given parameters')
else:
for i in range(length):
# generate a random integer, leaving space
# for enough others given the various requirements...
randVal = random.randint(x, high-factor*(length-i))
# add to list
randVals.append(randVal)
x = randVal + factor
print(randVals)
# if we want, we can shuffle the list
random.shuffle(randVals)
print(randVals)
TA贡献1854条经验 获得超8个赞
您可以执行以下操作:
from random import sample
def random_list(spacing, k=5, lo=10, hi=502):
return sample(list(range(lo, hi+1, spacing)), k=k)
result = random_list(64, k=5)
print(result)
输出 (随机)
[10, 458, 394, 266, 330]
随着list(range(lo, hi+1, spacing))您生成 10 到 502 之间的所有数字,步长为 64,然后使用sample从该总体中随机选择k数字。
添加回答
举报