1. 程式人生 > >py001- random中sample()函式的用法

py001- random中sample()函式的用法

sample(list, k)返回一個長度為k新列表,新列表存放list所產生k個隨機不重複的元素

函式用法例項:

import random

list = [1, 2, 3]
print(random.sample(list ,2))

list = ["china","python","sky"]
print(random.sample(list ,2))

list = range(1, 10000)
print(random.sample(list ,5))

輸出:
[1, 2]
['python', 'sky']
[6912, 1869, 5991, 721, 3388
]