3 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用儲(chǔ)層取樣。這是一個(gè)非常簡單的算法,適用于任何算法N。
這是一個(gè)Python實(shí)現(xiàn),這是另一個(gè)。

TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果您的序列足夠短,以至于可以將其讀入內(nèi)存并對其進(jìn)行隨機(jī)排序,那么一種簡單的方法就是使用random.shuffle:
import random
arr=[1,2,3,4]
# In-place shuffle
random.shuffle(arr)
# Take the first 2 elements of the now randomized array
print arr[0:2]
[1, 3]
根據(jù)序列的類型,您可能需要通過調(diào)用將其轉(zhuǎn)換為列表list(your_sequence),但是不管序列中對象的類型如何,此方法都可以工作。
自然,如果您無法將序列適合內(nèi)存,或者此方法對內(nèi)存或CPU的要求過高,則需要使用其他解決方案。

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個(gè)贊
import random
my_list = [1, 2, 3, 4, 5]
num_selections = 2
new_list = random.sample(my_list, num_selections)
# To preserve the order of the list, you could do:
randIndex = random.sample(range(len(my_list)), n_selections)
randIndex.sort()
new_list = [my_list[i] for i in randIndex]
添加回答
舉報(bào)