英文文檔:
range
(stop) range
(start, stop[, step])range
is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.說明:
>>> a = range(5) >>> a range(0, 5) >>> len(a) 5 >>> for x in a:print(x) 1 >>> b = range(0) # 傳入0,空range對象 >>> len(b) >>> c = range(-5) # 傳入負數,空range對象 >>> len(c) 0
3. 可以傳入一個起始整數和一個結束整數來初始化一個range類型,生成的range類型包含起始整數(包含),和結束整數(不包含)之間的所有整數。
>>> a = range(1,5) >>> a range(1, 5) >>> for x in a:print(x) 1 4
4. 傳入了起始整數和結束整數,還可以同時傳入一個步進值來初始化一個range類型,生成的range類型包含起始整數(包含),和結束整數(不包含)之間的以步進值篩選後的整數。
>>> a = range(1,10,3) >>> a range(1, 10, 3) >>> for x in a:print(x) 1 7
5. 初始化range類型時起始整數和結束整數,遵循的是左臂右開原則,即包含起始整數,但不包含結束整數。
>>> a = range(1,5) >>> a range(1, 5) >>> for x in a:print(x) # 包含1,不包含5 4
6. range接收的參數都必須是整數,不能是浮點數等其它數據類型。
>>> a = range(3.5) Traceback (most recent call last): File "<pyshell#33>", line 1, in <module> a = range(3.5) TypeError: 'float' object cannot be interpreted as an integer >>> a = range('3.5') Traceback (most recent call last): File "<pyshell#34>", line 1, in <module> a = range('3.5') TypeError: 'str' object cannot be interpreted as an integer
7. range實際上是一個不可變的序列類型,可以對它進行取元素、切片等序列操作,但是不能對其中元素修改值。
>>> a = range(1,5) >>> a[0] # 取元素 >>> a[:-2] # 切片 range(1, 3) >>> a[1] = 2 # 修改元素值 Traceback (most recent call last): File "<pyshell#38>", line 1, in <module> a[1] = 2 TypeError: 'range' object does not support item assignment