📜  Python range() 方法

📅  最后修改于: 2022-05-13 01:54:23.092000             🧑  作者: Mango

Python range() 方法

Python中有许多可迭代对象,例如列表、元组等。 range()提供了另一种使用某些条件初始化数字序列的方法。
range()通常用于 for 循环,因此,在处理任何类型的Python代码时,相同的知识是关键方面。

代码 #1:演示 range() 没有 step 参数

Python3
# Python3 code to demonstrate the
# working of range() without step
 
# using range()
lis1 = list(range(6))
lis2 = list(range(3, 6))
lis3 = list(range(-6, 2))
 
# initializing list using range, 1 parameter
# only stop parameter
print("List generated using 1 parameter : " + str(lis1))
 
# initializing list using range, 2 parameters
# only step and stop parameters
print("List generated using 2 parameters : " + str(lis2))
 
# initializing list using range, 2 parameter
# only step and stop parameters
print("List generated using 2 parameters with negatives : " + str(lis3))


Python3
# Python 3 code to demonstrate the
# working of range() with step
 
# initializing list using range
# using step
print("List generated using step : " +
    str(list(range(3, 10, 2))))
 
# initializing list using range
# using negative step
print("List generated using negative step : " +
                  str(list(range(10, -5, -3))))
 
# initializing list using range
# using negative step,
# value constraints fail case
print("List generated using step, value constraints fail : " +
                                 str(list(range(10, -5, 3))))
 
# initializing list using range
# using 0 step
# error
print("List generated using 0 step : " +
              str(list(range(3, 7, 0))))


输出:

List generated using 1 parameter : [0, 1, 2, 3, 4, 5]
List generated using 2 parameters : [3, 4, 5]
List generated using 2 parameters with negatives : [-6, -5, -4, -3, -2, -1, 0, 1]


代码 #2:使用 step 演示 range()

Python3

# Python 3 code to demonstrate the
# working of range() with step
 
# initializing list using range
# using step
print("List generated using step : " +
    str(list(range(3, 10, 2))))
 
# initializing list using range
# using negative step
print("List generated using negative step : " +
                  str(list(range(10, -5, -3))))
 
# initializing list using range
# using negative step,
# value constraints fail case
print("List generated using step, value constraints fail : " +
                                 str(list(range(10, -5, 3))))
 
# initializing list using range
# using 0 step
# error
print("List generated using 0 step : " +
              str(list(range(3, 7, 0))))

输出:

List generated using step : [3, 5, 7, 9]
List generated using negative step : [10, 7, 4, 1, -2]
List generated using step, value constraints fail : []

例外:

Traceback (most recent call last):
  File "/home/bdae725dff7b38d3681eee38f6a6d434.py", line 23, in 
    print("List generated using 0 step : " + str(list(range(3, 7, 0))))
ValueError: range() arg 3 must not be zero