range()函数详解

python range() 函数可创建一个整数列表,一般用在 for 循环中。
使用方式: range(start, stop[, step])

  • start: 计数从 start 开始。默认是从 0 开始。range(4) 相当于 range(0,4)
  • stop: 计数到 stop 结束,不包括 stop。range(0,4) 表达 [0, 1, 2, 3]
  • step:步长,默认为1。range(0,3) 相当于 range(0, 3, 1)
>>> list(range(5,10))
[5, 6, 7, 8, 9]
>>> list(range(15,10))
[]
>>> list(range(15,10,-1))
[15, 14, 13, 12, 11]

因为range函数的start和step都有默认值,因此一般我们都是直接给stop参数。但是有时候我们需要一个逆序的列表,这个时候我们需要指定三个参数并且step=-1即可。

猜你喜欢

转载自www.cnblogs.com/marvin-wen/p/12283755.html