簡體   English   中英

Python隨機函數從值列表中選擇一個新項目

[英]Python random function to select a new item from a list of values

我需要從Python的值列表中獲取隨機數。 我嘗試使用random.choice()函數,但有時會連續返回相同的值。 我想每次從列表中返回新的隨機值。 Python中是否有任何函數可以執行此類操作?

創建列表的副本,對其進行隨機排序,然后在需要新的隨機值時從其中一個彈出項目:

shuffled = origlist[:]
random.shuffle(shuffled)

def produce_random_value():
    return shuffled.pop()

保證不會重復元素。 但是,您可以用盡所有可用的數字,這時您可以再次復制並重新隨機播放。

要連續執行此操作,可以使它成為生成器函數:

def produce_randomly_from(items):
    while True:
        shuffled = list(items)
        random.shuffle(shuffled)
        while shuffled:
            yield shuffled.pop()

然后在循環中使用它,或通過next()函數獲取新值:

random_items = produce_randomly_from(inputsequence)
# grab one random value from the sequence
random_item = next(random_items)

這是一個例子:

>>> random.sample(range(10), 10)
[9, 5, 2, 0, 6, 3, 1, 8, 7, 4]

只需將范圍給定的序列替換為您要選擇的序列即可。 第二個數字是多少個樣本,應該是輸入序列的長度。

如果只想避免連續的隨機值,則可以嘗試以下操作:

import random
def nonrepeating_rand(n):
    ''' Generate random numbers in [0, n) such that no two consecutive numbers are equal. '''
    k = random.randrange(n)
    while 1:
        yield k
        k2 = random.randrange(n-1)
        if k2 >= k: # Skip over the previous number
            k2 += 1
        k = k2

測試:

for i,j in zip(range(25), nonrepeating_rand(3)):
    print i,j

打印(例如)

0 1
1 0
2 2
3 0
4 2
5 0
6 2
7 1
8 0
9 1
10 0
11 2
12 0
13 1
14 0
15 2
16 1
17 0
18 2
19 1
20 0
21 2
22 1
23 2
24 0

您可以使用nonrepeating_rand(len(your_list))獲得列表的隨機索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM