从python容器中随机选取元素

 1 # 1.使用python random模块的choice方法随机选择某个元素
 2 import random
 3 
 4 foo = ['a', 'b', 'c', 'd', 'e']
 5 from random import choice
 6 
 7 print(choice(foo))
 8 
 9 # 2.使用python random模块的sample函数从列表中随机选择一组元素
10 list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
11 # 设置种子使得每次抽样结果相同
12 random.seed(10)
13 slice = random.sample(list, 5)  # 从list中随机获取5个元素,作为一个片断返回
14 
15 print(slice)
16 print(list)  # 原有序列并没有改变。

转载:https://blog.csdn.net/liu3237/article/details/48416969

猜你喜欢

转载自www.cnblogs.com/tan-wm/p/9958648.html
今日推荐