頭文件: import random 1、生成一個隨機浮點數,范圍是0-1: print random.random() 2、生成指定范圍內的隨機浮點數: print random.uniform(a,b) 3、生成指定范圍內的隨機整數: print random.randint(a,b) 4、生成指定范圍內的任意數: print randrange(a,b) 生成指定范圍內的任意n個遞增序列: print randrange(a,b,n) 5、隨機獲取一個元素 random.choice(sequence) random.choice("Hello world!") random.choice(("Hello world!")) random.choice(["Hello world"]) random.choice("Hello","world") random.choice(("Hello","world")) random.choice(["Hello","world"]) 6、將元素打亂 import random list=['I','love','Python'] random.shuffle(list) print list 7、從一個序列中隨機選擇n個元素,不改變原始序列 import random a="123456" b=[1,2,3,4,5,6] c=['a','b','c','d','e'] print random.sample(a,3) print random.sample(b,3) print random.sample(c,3) 另: a=["123456"] b="123456"
