亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使列表中的隨機值至少在Python列表中的每個值的給定數量上是唯一的?

如何使列表中的隨機值至少在Python列表中的每個值的給定數量上是唯一的?

紅顏莎娜 2022-10-06 18:36:39
所以我對python相當陌生。我正在嘗試創建一個具有唯一隨機值的列表,這些隨機值與列表中的每個其他隨機值至少相差一個給定因子,并且都以兩個值為界。例如,我想要一個類似的列表:randVals = [24, 418, 100, 286, 350]其中每個值彼此之間的唯一性至少為給定因子 64?,F在,我的代碼:import randomx = [1, 2, 3, 4, 5]randVals = [0] * (len(x) + 1)factor = 64print(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]
查看完整描述

2 回答

?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

首先,讓我們確保我理解您要執行的操作:“我正在嘗試創建一個具有唯一隨機值的列表,這些隨機值至少成對地相差一個給定的因子,并且都以兩個值為界。” “我試圖讓所有值都在 10 到 502 之間,而列表中的所有值至少相隔 64 個單位或更多?!?/p>


然后,按照您的使用方法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)


查看完整回答
反對 回復 2022-10-06
?
嗶嗶one

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數字。


查看完整回答
反對 回復 2022-10-06
  • 2 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號