你可以使用random.sample
功能從standard library選擇從ķ元素人口:
import random
random.sample(range(low, high), n)
在相當大的情況下,可能的數字範圍,你可以使用itertools.islice
具有無限隨機生成:
import itertools
import random
def random_gen(low, high):
while True:
yield random.randrange(low, high)
gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10)) # take first 10 random elements
UPDATE
所以,問題後更新現在很清楚,你需要ñ不同的(唯一的)數字。
import itertools
import random
def random_gen(low, high):
while True:
yield random.randrange(low, high)
gen = random_gen(1, 100)
items = set()
# try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
items.add(x)
請看:[創建在Python整數隨機列表(http://stackoverflow.com/questions/4172131/create-random-list-of-integers-in-python)。 – alecxe
如何爲StackExchange本身提供建議。不應該重複的通知包含重複的鏈接? –