random.sample
函数返回包含列表中任意两个项目的列表:
import random
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for i in range(3):
slice_a = random.sample(a, 5) # 从list中随机获取5个元素,作为一个片断返回
print(slice_a)
print(a, '\n') # 原有序列并没有改变
输出:
[15, 7, 10, 13, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[12, 4, 9, 13, 15]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[6, 1, 7, 9, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
发现每一次的random.sample函数返回的5个元素不同