Python內建函數(58)——slice,python內建58slice

來源:互聯網
上載者:User

Python內建函數(58)——slice,python內建58slice

英文文檔:

class slice( stop)
class slice( start, stop[, step])
Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

 

說明:

  1. 函數實際上是一個切片類的建構函式,返回一個切片對象。

  2. 切片對象由3個屬性start、stop、step組成,start和step預設值為None。切片對象主要用於對序列對象進行切片取對應元素。

>>> help(slice)class slice(object) |  slice(stop) |  slice(start, stop[, step]) |   |  Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]). |   |  Methods defined here: |   |  ...#省略# |  ---------------------------------------------------------------------- |  Data descriptors defined here: |   |  start |   |  step |   |  stop |   |  ---------------------------------------------------------------------- |  Data and other attributes defined here: |   |  __hash__ = None
>>> a = list(range(10))>>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> a[None:5:None] # start step顯式為None[0, 1, 2, 3, 4]>>> a[:5:] # start step預設為None[0, 1, 2, 3, 4]>>> a[2:5:None] # step顯式為None[2, 3, 4]>>> a[2:5:] # step預設為None[2, 3, 4]>>> a[1:10:3][1, 4, 7]

  3. 對應切片對象的3個屬性start、stop、step,slice函數也有3個對應的參數start、stop、step,其值分別會付給切片對象的start、stop、step。

>>> c1 = slice(5) # 定義c1>>> c1slice(None, 5, None)>>> c2 = slice(2,5) # 定義c2>>> c2slice(2, 5, None)>>> c3 = slice(1,10,3) # 定義c3>>> c3slice(1, 10, 3)>>> a[c1] # 和a[:5:]結果相同[0, 1, 2, 3, 4]>>> a[c2] # 和a[2:5:]結果相同[2, 3, 4]>>> a[c3] # 和a[1:10:3]結果相同[1, 4, 7]

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.