1. 程式人生 > >python技巧——從list中隨機抽取元素的方法

python技巧——從list中隨機抽取元素的方法

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) to high (exclusive).