3 回答

TA貢獻1744條經(jīng)驗 獲得超4個贊
如果您的序列足夠短,以至于可以將其讀入內(nèi)存并對其進行隨機排序,那么一種簡單的方法就是使用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貢獻1842條經(jīng)驗 獲得超21個贊
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]
添加回答
舉報