1、range()函数
>>> temp = range(1, 5) >>> print(temp) range(1, 5) >>> print(type(temp)) <class 'range'>
>>> list(temp)
[1, 2, 3, 4]
range(stop)
range(start, stop[, step])
参数说明:
- start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
- stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
- step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
>>> temp = range(1, 5) >>> print(temp) [1, 2, 3, 4] >>> print(type(temp)) <type 'list'>
以下在python3中实验
range()函数一般结合for循环使用,例如遍历一个列表时,如果要通过列表的下标来打印每个元素,则可以通过range()函数实现
>>> nums = ["a","b","c","d","e"] >>> for i in range(len(nums)): print(nums[i]) a b c d e
random模块
当需要生成随机数或者从一个列表中随机取一条或多条数据时,会使用到random模块
1、生成的随机数
>>> random.randint(32768, 66538)
39701
2、从一组数据中随机获取一个元素
>>> random.choice([1,2,3,4,5]) 1 >>> random.choice([1,2,3,4,5]) 5
3、从一组数据中随机获取n个元素
使用random.sample(sequence, n)可以从列表,元组或字符串中随机获取n个元素,且不重复
>>> l = [1,2,3,4,5] >>> random.sample(l,3) [4, 1, 5] >>> random.sample(l,3) [4, 2, 3] >>> random.sample(l,4) [4, 1, 5, 3] >>> l [1, 2, 3, 4, 5] # 原序列l没有变化
一个实际场景
count = random.choice(range(1, total+1))
total 表示查询到的数据总数,