python技巧——從list中隨機抽取元素的方法
阿新 • • 發佈:2018-12-04
1、隨機抽取一個元素
from random import choice
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(choice(l)) # 隨機抽取一個
可能的一種輸出:
3
對 choice(seq)
的解釋:
Choose a random element from a non-empty sequence.
2、隨機抽取若干個元素(無重複)
from random import sample
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(sample( l, 5)) # 隨機抽取5個元素
可能的一種輸出:
[8, 3, 4, 9, 10]
對 sample(population, k)
的解釋:
Chooses k unique random elements from a population sequence or set.
3、隨機抽取若干個元素(有重複)
import numpy as np
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
idxs = np.random.randint(0, len(l), size=5) # 生成長度為5的隨機陣列,範圍為 [0,10),作為索引
print([l[i] for i in idxs]) # 按照索引,去l中獲取到對應的值
可能的一種輸出:
[8, 8, 7, 4, 1]
對 randint(low, high=None, size=None, dtype='l')
的解釋:
Return random integers from
low
(inclusive) tohigh
(exclusive).