python中random模塊可以生成隨機數(shù)或隨機順序或隨機選擇
我們常用的有random, randint, randrange, shuffle, sample, uniform误墓,choice
- random: 隨機生成 [0,1) 的實數(shù)
import random
x = random.random()
print(x)
0.9065644990934733
- randint: 隨機生成 [min,max] 范圍內(nèi)的整數(shù)
import random
x = random.randint(1, 100)
print(x)
21
- randrange:隨機生成[start, stop,step]范圍內(nèi)的整數(shù) 設置step可以規(guī)定步長
import random
for _ in range(10): # 通過循環(huán)十次看看隨機生成的效果
x = random.randrange(1, 100, 2)# 隨機生成一到一百的奇數(shù)
print(x, end=' ') # 通過設置end讓結果打印在一排
53 27 1 51 31 65 13 15 87 93
- uniform:隨機生成[min,max]范圍內(nèi)的浮點數(shù)
import random
x = random.uniform(1,10)
print(x)
9.11079652346942
- shuffle: 將列表的順序打亂(列表按隨機排序)
import random
list1 = [1,2,3,4,5,6,7,8,9,10]
random.shuffle(list1) # 打亂列表順序
print(list1) # 原有列表已經(jīng)被隨機排序
[1, 6, 3, 7, 8, 5, 9, 4, 10, 2]
- sample:從容器中隨機選出指定數(shù)量的元素萍膛,容器可以是列表氏淑、字符串推掸、元組
import random
list1 = [1,2,3,4,5,6,7,8,9,10]
string1 = 'abcdefghijk'
tuple1 = (1,2,3,4,5,6,7,8,9,10)
x = random.sample(list1,3) # 隨機在list1中選取3個元素
y = random.sample(string1,3) # 隨機在字符串中選取三個元素
z = random.sample(tuple1,2) # 隨機在元組中選取兩個元素
print(x)
print(y)
print(z)
print(list1) # sample并不改變原有容器
print(string1)
print(tuple1)
[6, 4, 7]
['h', 'g', 'k']
[1, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
abcdefghijk
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
- choice:從容器中隨機選取一個元素,容器可以是列表绎秒、字符串呆盖、元組
import random
list1 = [1,2,3,4,5,6,7,8,9,10]
string1 = 'abcdefghijk'
tuple1 = (1,2,3,4,5,6,7,8,9,10)
x = random.choice(list1) # 隨機在list1中選取元素
y = random.choice(string1) # 隨機在字符串中選取元素
z = random.choice(tuple1) # 隨機在元組中選取元素
print(x)
print(y)
print(z)
print(list1) # choice并不改變原有容器
print(string1)
print(tuple1)
1
c
8
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
abcdefghijk
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)