关于python函数range(),xrange(),randrange(),randint()

1. range()

python range() 函数可创建一个整数列表,一般用在 for 循环中。

函数语法
range(start, stop[, step])

返回值:range

参数说明:
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)

注意:
Python3 range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。

Python3 list() 函数是对象迭代器,可以把range()返回的可迭代对象转为一个列表,返回的变量类型为列表。

Python2 range() 函数返回的是列表(与别与xrange(),python3中把xrange()取消,range()的功能取代了xrange())

2. xrange():

python2中range()直接返回值是list,比较占内存,xrange()返回生成器,python3中直接用range()取代了xrange()的功能,不再有直接返回list。

3.randrange():
randrange()是python3内置random模块下的一个生成随机数的函数,参数与range()相同,其功能相当于choice(range(start, stop, step)),但并不实际产生range对象,该函数返回值类型是int。

以下是官方文档的解释:
random.randrange(start, stop[, step])
Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

The positional argument pattern matches that of range(). Keyword arguments should not be used because the function may use them in unexpected ways.

Changed in version 3.2: randrange() is more sophisticated about producing equally distributed values. Formerly it used a style like int(random()*n) which could produce slightly uneven distributions.

4.randint(a,b)
这里附带介绍一下与randrange()功能近似的randint()函数,同样是从一个连续数组中产生一个随机数的函数,但参数与range()不一样。N = random.randint(a, b),N在此处的选择范围是a <= N <= b,是包含b的,选择randint()时要多加注意。
因此从功能上 randint(a,b) == randrange(a,b+1)

猜你喜欢

转载自blog.csdn.net/weixin_42999937/article/details/82881470