如何使列表中的随机值至少在Python列表中的每个值的给定数量上是唯一的?

所以我对python相当陌生。


我正在尝试创建一个具有唯一随机值的列表,这些随机值与列表中的每个其他随机值至少相差一个给定因子,并且都以两个值为界。


例如,我想要一个类似的列表:


randVals = [24, 418, 100, 286, 350]

其中每个值彼此之间的唯一性至少为给定因子 64。


现在,我的代码:


import random


x = [1, 2, 3, 4, 5]

randVals = [0] * (len(x) + 1)

factor = 64


print(randVals)


for i in range(len(randVals) - 1):

    randVals[i] = random.randint(10, 502)


    while randVals[i + 1] - factor <= randVals[i] <= randVals[i + 1] + factor:

        randVals[i] = random.randint(10, 502)

    print(randVals)


randVals.pop(len(x))

    print(randVals)

输出:


[0, 0, 0, 0, 0, 0]

[494, 0, 0, 0, 0, 0]

[494, 144, 0, 0, 0, 0]

[494, 144, 489, 0, 0, 0]

[494, 144, 489, 342, 0, 0]

[494, 144, 489, 342, 361, 0]

[494, 144, 489, 342, 361]


红颜莎娜
浏览 111回答 2
2回答

沧海一幻觉

首先,让我们确保我理解您要执行的操作:“我正在尝试创建一个具有唯一随机值的列表,这些随机值至少成对地相差一个给定的因子,并且都以两个值为界。” “我试图让所有值都在 10 到 502 之间,而列表中的所有值至少相隔 64 个单位或更多。”然后,按照您的使用方法random.randint:import random&nbsp; &nbsp; # to generate random valuesrandVals = []&nbsp; &nbsp; # and keep those values in a listfactor = 64&nbsp; &nbsp; &nbsp; # values should differ by this factorlow = 10&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# lower boundhigh = 502&nbsp; &nbsp; &nbsp; &nbsp;# upper boundx = low&nbsp; &nbsp; &nbsp;# start at lower boundlength = 8&nbsp; # list should be of this lengthif(high - factor*length)<low:&nbsp; &nbsp; print('Impossible to generate list with given parameters')else:&nbsp; &nbsp; for i in range(length):&nbsp; &nbsp; &nbsp; &nbsp; # generate a random integer, leaving space&nbsp; &nbsp; &nbsp; &nbsp; # for enough others given the various requirements...&nbsp; &nbsp; &nbsp; &nbsp; randVal = random.randint(x, high-factor*(length-i))&nbsp; &nbsp; &nbsp; &nbsp; # add to list&nbsp; &nbsp; &nbsp; &nbsp; randVals.append(randVal)&nbsp; &nbsp; &nbsp; &nbsp; x = randVal + factor&nbsp; &nbsp; print(randVals)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; # if we want, we can shuffle the list&nbsp; &nbsp; random.shuffle(randVals)&nbsp; &nbsp; print(randVals)

哔哔one

您可以执行以下操作:from random import sampledef random_list(spacing, k=5, lo=10, hi=502):&nbsp; &nbsp; 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数字。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java