3 回答

TA贡献1744条经验 获得超4个赞
如果您的序列足够短,以至于可以将其读入内存并对其进行随机排序,那么一种简单的方法就是使用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]
根据序列的类型,您可能需要通过调用将其转换为列表list(your_sequence),但是不管序列中对象的类型如何,此方法都可以工作。
自然,如果您无法将序列适合内存,或者此方法对内存或CPU的要求过高,则需要使用其他解决方案。

TA贡献1842条经验 获得超22个赞
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]
添加回答
举报