random模块常用函数:
from random import * # Random float: 0.0 <= x < 1.0 random() # Random float: 2.5 <= x < 10.0 uniform(2.5, 10.0) # Integer: 0 <= x <= 9 randrange(10) # Even integer from 0 to 100 inclusive randrange(0, 101, 2) # Single random element from a sequence choice(['win', 'lose', 'draw']) # 打乱序列元素顺序,注意是对原序列操作,不会产生新序列,因此要求原序列是可改变的 deck = 'ace two three four'.split() shuffle(deck)
items = [1, 2, 3, 4, 5, 6]
random.shuffle(items)
print(items) #返回从序列中选取k个不重复元素的列表(产生新序列,不改变原序列,因此原序列可以为元组、字符串等) sample([10, 20, 30, 40, 50], k=4)
''.join(random.sample('abcdefghijklmnopqrst', 5)) sample(range(10000),30) #要打乱元组或字符串的顺序,可以变通的使用sample() atuple=(1,2,3,4,5,6,7) sample(atuple, len(atuple))