Python內建函數(52)——range

來源:互聯網
上載者:User

標籤:資料   erp   tab   ror   ret   item   rac   cti   table   

英文文檔:

range( stop)
range( start, stop[, step])
Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.

說明:

  1. range函數用於產生一個range對象,range類型是一個表示整數範圍的類型。
  2. 可以直接傳入一個結束整數來初始化一個range類型,預設起始值為0(包含0).結束整數可以大於0,也可以小於等於0,但是小於等於0的時候產生的range對象實際是不包含任何元素的。
>>> a = range(5)>>> arange(0, 5)>>> len(a)5>>> for x in a:print(x)01234>>> b = range(0) # 傳入0,空range對象>>> len(b)0>>> c = range(-5)  # 傳入負數,空range對象>>> len(c)0

  3. 可以傳入一個起始整數和一個結束整數來初始化一個range類型,產生的range類型包含起始整數(包含),和結束整數(不包含)之間的所有整數。

>>> a = range(1,5)>>> arange(1, 5)>>> for x in a:print(x)1234

  4. 傳入了起始整數和結束整數,還可以同時傳入一個步進值來初始化一個range類型,產生的range類型包含起始整數(包含),和結束整數(不包含)之間的以步進值篩選後的整數。

>>> a = range(1,10,3)>>> arange(1, 10, 3)>>> for x in a:print(x)147

  5. 初始化range類型時起始整數和結束整數,遵循的是左臂右開原則,即包含起始整數,但不包含結束整數。

>>> a = range(1,5)>>> arange(1, 5) >>> for x in a:print(x) # 包含1,不包含51234

  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] # 取元素1>>> a[:-2] # 切片range(1, 3)>>> a[1] = 2 # 修改元素值Traceback (most recent call last):  File "<pyshell#38>", line 1, in <module>    a[1] = 2TypeError: ‘range‘ object does not support item assignment

 

 

Python內建函數(52)——range

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.