python之random函數


# random各種使用方法
import random

# 隨機生成[0.1)的浮點數
print("random():", random.random())

# 隨機生成1000-9999之間的整數
print("randint(1000, 9999):", random.randint(1000, 9999))

# 隨機生成0-20之間的偶數
print("randrange(0, 21, 2):", random.randrange(0, 21, 2))

# 隨機生成0-20之間的浮點數
print("uniform(0, 20):", random.uniform(0, 20))

# 從序列中隨機選擇一個元素
list_string = ['a', 'b', 'c', 'd', 'e']
print("choice(list):", random.choice(list_string))
print("choice(string):", random.choice('abcd'))

# 對列表元素隨機排序
list_number = [1, 2, 3, 4, 5]
random.shuffle(list_number)
print("shuffle(list):", list_number)

# 從指定序列中隨機獲取指定長度的片斷
print("sample(sequence):", random.sample('abcdefg', 2))

 運行結果:

random(): 0.6708362810735843
randint(1000, 9999): 5228
randrange(0, 21, 2): 6
uniform(0, 20): 12.767906137387294
choice(list): a
choice(string): d
shuffle(list): [1, 3, 5, 2, 4]
sample(sequence): ['f', 'g']

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM