python之random模块,,# 关于random
python之random模块,,# 关于random
# 关于random模块的简单应用random.random() # 生成0-1的随机数a = random.uniform(1, 10) # 1-10之间的一个随机数b = random.randint(1, 10) # 1-10之间的一个随机整数 c = random.randrange(0, 100, 2) # 从0开始到100结束,步长为2的序列中,随机选取一个在0到100之间偶数lst = [‘dsd‘,‘fds‘,‘dsf‘,‘dd‘,‘dqe‘]d = random.choice(lst) # 从序列(字符串、列表、元组)中随机选一个random.shuffle(lst) # 重新排列序列e = random.sample(lst, 5) # 从序列中随机取样5个(多个)print(a,b,c,d,lst,e)
当需要生成批量数据来练习或者工作需要时,利用random模块随机生成数字、单词、密码等等,这绝对是个不错的选择!
import randomdef custom_generate(character=‘abcdefghijklmnopqrstuvwxyz0123456789‘, length=5, number=1): ‘‘‘ 定义函数custom_generate ---》用于自定义生成字符串 - character 定义可选特征字符 - length 字符长度 - number 生成的个数 ‘‘‘ character_list = list(character) # 将字符串转为列表 custom_list = [] # 定义空列表 while number: # 限制循环次数即生成个数,默认值为1 generate = random.sample(character_list, length) # 利用random.sample对character_list随机取样,默认值为5 custom = ‘‘.join(generate) # 列表转为字符串, custom_list.append(custom) # 字符串添加到列表 number -= 1 # number运行一次减一,直到为0,while False而终止循环 if len(custom_list) == 1: # 列表里生成的个数为1,直接返回字符串 return custom_list[0] else: return custom_list # 返回字符串列表
类似的,可举一反三!重要的是,能在后面的学习和工作中用上自己写的函数这应该是件快乐的事情。
def word(length=5, number=1): ‘‘‘随机生成单词‘‘‘ character = ‘abcdefghijklmnopqrstuvwxyz‘ letter_list = list(character) word_list = [] while number: generate = random.sample(letter_list,length) word = ‘‘.join(generate) word_list.append(word) number -= 1 if len(word_list) == 1: return word_list[0] else: return word_listdef digit(start=0,end=100,number=1): ‘‘‘随机生成数字‘‘‘ digit_list =[] while number: generate_digit = random.choice(range(start,end)) digit_list.append(generate_digit) number -= 1 if len(digit_list) == 1: digit = digit_list[0] return digit else: return digit_listdef password(length=8,number=1): ‘‘‘随机生成密码‘‘‘ character = ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ|_!.$#*&^~0123456789‘ character_list = list(character) password_list = [] while number: generate = random.sample(character_list,length) password = ‘‘.join(generate) password_list.append(password) number -= 1 if len(password_list) == 1: return password_list[0] else: return password_list
python之random模块
相关内容
- 使用pep8 vim插件规范Python代码,,安装PEP81.su
- python request 接口测试get和post请求,pythonrequest,开发IDE:
- Python图表数据可视化Seaborn:4结构化图表可视化,,1.基
- Python pandas DataFrame操作,,1. 从字典创建Da
- Python中关于列表排序并保留id,python排序保留id,新手才
- python ---求100以内的质数有哪些,,#coding=ut
- 粗解python的@classmethod和@staticmethod及普通实例方法,,引
- mysql与python3交互,,ubuntu端安装s
- CentOS7安装Python3.7,,首先安装依赖包,ce
- python:argparse命令行解析模块详解,,argparse命令
评论关闭