Python基础之random

tech2024-06-06  71

Python基础之random

本节将介绍Python中的内置模块random,用于随机数相关的操作。


random模块支持生成随机浮点数,随机整数,从list,tuple,str 中随机选择某一个或多个元素,混淆某个list。例如:

import random import string # float_n is a float number in [0,1) float_n = random.random() print(float_n) # int_n is a int number in [1, 10] int_n = random.randint(1, 10) print(int_n) # float_n is a float number in [1.2, 2.8] float_n = random.uniform(1.2, 2.8) print(float_n) # Random choice print(random.choice("abcdefghi")) print(random.choice([1, 2, 3, 4, 5, 6])) print(random.choice(('xiaoming', 'xiaohong', 'ahuang', 'tom', 'jerry'))) # Random range in [1, 10) with step 2 print(random.randrange(1, 10, 2)) # Shuffle a list l = [1, 2, 3, 4, 5, 6, 7, 8, 9] random.shuffle(l) print(l) def generate_password(): while True: lower_l = random.sample(string.ascii_lowercase, random.randint(1, 5)) upper_l = random.sample(string.ascii_uppercase, random.randint(1, 5)) punc_l = random.sample(string.punctuation, random.randint(1, 5)) digit_l = random.sample(string.digits, random.randint(1, 5)) password_l = lower_l + upper_l + punc_l + digit_l random.shuffle(password_l) password_str = ''.join(password_l) if len(password_str) >= 12: return password_str else: print("Generate password again...") password = generate_password() print(password)

运行结果:

D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_14/test_random.py 0.5892891534926099 7 2.0257998459688524 e 6 xiaoming 1 [7, 5, 2, 8, 1, 6, 3, 9, 4] Generate password again... Pmn`{4]x+7v$U Process finished with exit code 0

 

最新回复(0)