介绍
random.sample()函数是Python标准库中random模块中的一个函数,用于从序列中随机抽取指定数量的元素。
用法
random.sample(list, k)
其中,list
是要进行抽样的序列,可以是列表、元组、字符串等;k
是要抽取的元素个数。
实例
import random
list1 = [1, 2, 3]
print(random.sample(list1, 2))
list2 = ["china", "python", "sky"]
print(random.sample(list2, 2))
list3 = range(1, 1000)
print(random.sample(list3, 6))
输出:
[2, 1]
['sky', 'python']
[904, 176, 668, 171, 870, 908]