random模块包含生成伪随机数的函数。
random() 返回一个[0,1)范围内的随机实数,0<=N<1
import random for i in range(10): print(random.random()) '''结果: 0.47202739271730954 0.9954537367866398 0.8966889393590349 0.21526504257867707 0.5177143830734733 0.07058972065059876 0.7639556906894629 0.7694914888493678 0.7644288481584427 0.6503337295897702 '''
uniform(a,b) 返回一个[a,b]范围内的随机实数,当a<=b时a<=N<=b,当b<a时b<=N<=a
import random for i in range(10): print(random.uniform(1,10)) '''结果: 8.309065298004139 3.6646029190795475 5.120157436641914 7.844513020549868 2.2798871584948484 8.263853186222267 4.956861193252699 6.104021085632928 9.585461204997616 4.3073243526217615 '''
randrange([start],stop,[step]) 从range(start,stop,step)中随机返回一个整数,a<=N<b
import random for i in range(10): print(random.randrange(1,10)) '''结果: 6 5 3 4 3 1 1 1 9 4 ''' for i in range(10): print(random.randrange(1,10,2)) '''结果: 1 7 7 1 1 9 9 3 1 5 '''
randint(a,b) 返回一个[a,b]范围内的随机整数,a<=N<=b,相当于randrange(a, b+1)。
import random for i in range(10): print(random.randint(1,10)) '''结果: 2 7 2 1 4 6 10 5 10 8 '''
choice(seq) 从序列seq中随机地选择一个元素
import random list1 = [1,2,4,8] print(random.choice(list1)) #结果:4 tup1 = (1,2,4,8) print(random.choice(tup1)) #结果:2
shuffle(seq[, random]) 打乱序列seq
import random list1 = [1,2,4,8] print(list1) #结果:[1, 2, 4, 8] random.shuffle(list1) print(list1) #结果:[1, 8, 4, 2]
sample(seq,n) 从序列中随机地选择n个值不同的元素
import random list1 = [1,2,2,4,4,8] for i in list1: print(random.sample(list1,2)) '''结果: [2, 4] [8, 1] [4, 2] [4, 2] [1, 2] [4, 2] '''