One - One Code All

Blog Content

python random从集合中随机选择元素

Python   2010-06-10 22:29:59

随机选择某个元素:

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


随机选择一组元素:

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



上一篇:pip --upgrade批量更新过期的python库
下一篇:python遍历字典并修改,错误:dictionary changed size during iteration

The minute you think of giving up, think of the reason why you held on so long.