python随机选择list中的元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37876745/article/details/84853202

使用python random模块的choice方法随机选择某个元素

foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
print choice(foo)

使用python random模块的sample函数从列表中随机选择一组元素

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
slice = random.sample(list, 5)  #从list中随机获取5个元素,作为一个片断返回  
print slice  
print list #原有序列并没有改变。  

猜你喜欢

转载自blog.csdn.net/m0_37876745/article/details/84853202