Python顺序与range和random
2016-01-05 17:04
766 查看
range([start,] stop[, step]) start是开始,stop是停下,step是步长。
>>> random.random() #随机生成一个0到1的浮点数
0.6120230917948929
>>> range(10) range(0, 10) >>> list(range(10)) #生成一个0到9之间的序列 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(1,10)) #生成1到9的序列 [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(1,10,2)) #生成1到9的序列,步长为2 [1, 3, 5, 7, 9] >>> list(reversed(range(10))) #生成一个倒着的序列 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> list(range(10,-3,-1)) #也可以是负数 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2]
>>> import random
>>> random.random() #随机生成一个0到1的浮点数
0.6120230917948929
>>> random.uniform(3,10) #生成范围内的浮点数 5.105005760923818 >>> random.uniform(-10,-2) #也可以是负数 -8.054425235362464 >>> random.randint(10,15) #生成10到15之间的随机数,求概率常用 15 >>> random.randint(10,15) 10 >>> random.randint(10,15) 12 >>> random.randrange(10,20,3)#10到20,步长为3 10 >>> random.randrange(10,20,3) 19 >>> random.randrange(10,20,3) 10 >>> random.randrange(10,20,3) 16 >>> random.choice(list(range(10,20,3))) #同上,随机选择list中的一个元素返回 19 >>> random.choice(['str1','str2','str3','str4']) 'str1' >>> a =['str1',12,'str3','str4',123,111] >>> random.shuffle(a) #这个常用来打乱顺序 >>> a ['str3', 123, 12, 'str1', 'str4', 111] >>> random.shuffle(a) >>> a [12, 'str1', 123, 111, 'str4', 'str3'] >>> random.shuffle(a) >>> a ['str1', 'str4', 111, 12, 'str3', 123]
>>> random.sample(a,2) #随机选择列表a中的两个元素返回 [123, 'str3'] >>> random.sample(a,2) ['str4', 111] >>> random.sample(a,2) [123, 12] >>>参考连接:http://bbs.fishc.com/forum.php?mod=viewthread&tid=54578
相关文章推荐
- python+interface testing 读写Excel需要的包
- python--list和tuple类型--2
- python 操作mysql数据库
- python的运算符重载
- python实例编写(7)---测试报告与测试套件(多个py文件,1个py文件内多个用例)
- python 数据类型之list
- python入门笔记(2)
- leetcode之3Sum
- Python学习笔记8-类的继承 、深度优先、广度优先
- Python学习笔记8-类的继承 、深度优先、广度优先
- python 数据类型之数float
- python常用的转义字符
- python 新式类与旧式类
- Python 版本3和版本2 的字符串格式化区别 ----%s
- python--数据类型--1
- Python + Socket 通信
- Python logging模块详解
- 转载:浅析Python中的多进程与多线程的使用
- 零基础入门学习Python(27):模块和包
- python 数据类型之数值型