Python3.5内置模块之random模块用法实例分析

yipeiwu_com7年前Python基础

本文实例讲述了Python3.5内置模块之random模块用法。分享给大家供大家参考,具体如下:

1、random模块基础的方法

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import random
print(random.random())     #随机产生[0,1)之间的浮点值
print(random.randint(1,6))   #随机生成指定范围[a,b]的整数
print(random.randrange(1,3))  #随机生成指定范围[a,b)的整数
print(random.randrange(0,101,2)) ##随机生成指定范围[a,b)的指定步长的数(2--偶数)
print(random.choice("hello")) #随机生成指定字符串中的元素
print(random.choice([1,2,3,4])) #随机生成指定列表中的元素
print(random.choice(("abc","123","liu"))) #随机生成指定元组中的元素
print(random.sample("hello",3))  #随机生成指定序列中的指定个数的元素
print(random.uniform(1,10))   #随机生成指定区间的浮点数
#洗牌
items = [1,2,3,4,5,6,7,8,9,0]
print("洗牌前:",items)
random.shuffle(items)
print("洗牌后:",items)

运行结果:

0.1894544287915626
2
1
74
l
2
liu
['l', 'h', 'o']
1.2919229440123967
洗牌前: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
洗牌后: [6, 9, 2, 7, 1, 3, 8, 5, 4, 0]

2、random模块中方法的实际应用——生成随机验证码

(1)随机生成4位纯数字验证码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import random
check_code = ''  #最终生成的验证码
for i in range(4):    #4位长的纯数字验证码
  cur = random.randint(0,9)
  check_code += str(cur)
print(check_code)

运行结果:

0671

(2)随机生成4位字符串验证码(数字与字符都有)

import random
check_code = ''
for i in range(4):
  cur = random.randrange(0,4)  #随机猜的范围,与循环次数相等
  #字母
  if cur == i:
    tmp = chr(random.randint(65,90))  #随机取一个字母
  #数字
  else:
    tmp = random.randint(0,9)
  check_code += str(tmp)
print(check_code)

运行结果:

39HN

PS:这里再提供几款相关工具供大家参考使用:

在线随机数生成工具:
http://tools.jb51.net/aideddesign/rnd_num

在线随机生成个人信息数据工具:
http://tools.jb51.net/aideddesign/rnd_userinfo

在线随机字符/随机密码生成工具:
http://tools.jb51.net/aideddesign/rnd_password

在线随机数字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python数组条件过滤filter函数使用示例

使用filter函数,实现一个条件判断函数即可。 比如想过滤掉字符串数组中某个敏感词,示范代码如下: #filter out some unwanted tags def pass...

如何使用Python进行OCR识别图片中的文字

朋友需要一个工具,将图片中的文字提取出来。我帮他在网上找了一些OCR的应用,都不好用。所以准备自己研究,写一个Web APP供他使用。 OCR1,全称Optical character...

python中bytes和str类型的区别

经过一上午的查找资料。大概理清楚了bytes类型和str类型的区别。 bytes类型和str类型在呈现形式有相同之处,如果你print一个bytes类型的变量,会打印一个用b开头,用单引...

Python 多线程搜索txt文件的内容,并写入搜到的内容(Lock)方法

废话不多说,直接上代码吧! import threading import os class Find(threading.Thread): #搜索数据的线程类 def __i...

python 实现矩阵填充0的例子

需求: 原矩阵 [[1 2 3] [4 5 6] [7 8 9]] 在原矩阵元素之间填充元素 0,得到 [[1. 0. 2. 0. 3.] [0. 0. 0. 0. 0....