[英]In python, how to generate a random integer in a range, excluding some numbers in a list?
例如,在開始時我想從(0,9)生成一個隨機整數,
第一次,程序生成2,然后我把2放在'排除'列表中,
下次,我需要生成一個介於0到9之間的數字,並排除2.讓我們說第二個轉彎,程序生成5。
第三回合,我需要生成一個從0到9的數字,不包括2和5。
由於范圍非常大(百萬級),有什么方法是有效的嗎?
生成一次可能的值,每次刷新該值並從該列表中彈出值:
values = range(10)
random.shuffle(values)
def get_value():
return values.pop()
這將最終以隨機順序產生該范圍內的所有值,而不重復。
根據random.sample
的文檔 :
要從一系列整數中選擇樣本,請使用
xrange()
對象作為參數。 這對於從大量人群中采樣來說特別快且節省空間:sample(xrange(10000000), 60)
。
這將在沒有替換的情況下進行采樣,因此random.sample(xrange(n), k)
在[0, n)
范圍內給出k
不同的數字(對於k <= n
)。
您可以使用將整數范圍映射到具有異常的相同整數范圍的函數,如下所示:
import random
def excection(val, exceptions):
''' Maps range of values into
similar range of values with exceptions missing.
Exceptions must be sorted increasingly.
for excample with exceptions=(2, 5) it will map
This: 0, 1, 2, 3, 4, 5, 6
To this: 0, 1, 3, 4, 6, 7, 8
'''
if not exceptions:
return val
for e in exceptions:
if val < e:
return val # value before any exclusion is unchanged
val += 1 # after some exclusion value is larger by one
return val
def randint_with_exceptions(min, max, exceptions):
r = random.randint(min, max - len(exceptions)) # generate random number in range smaller then desired by number of exceptions
return excection(r, exceptions) # and map it to desired, more sparse sequence
for i in range(20): # test possible randoms
print randint_with_exceptions(0, 7, (2, 5)),
from functools import partial
ex_25 = partial(excection, exceptions=(2, 5))
assert ( # unittest sequence transformation
map(ex_25, range(5))
== [0, 1, 3, 4, 6]
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.