如何通过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]

首先,让我们确保我理解您要做的事情:"我正试图用唯一的随机值列出一个列表,这些值至少以给定的因子成对不同,并且都以两个值为界。"我试图让所有值都在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)

您可以执行以下操作:

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)),以64为步长生成10到502之间的所有数字,然后使用sample从该群体中随机选择k数字。

最新更新