一般來說,內(nèi)置的slice()函數(shù)會(huì)創(chuàng)建一個(gè)切片對象,可以用在任何允許進(jìn)行切片操作的地方。
下面是slice的簡介:
1
2
3
|
# slice 兩種用法 class slice (stop) class slice (start, stop[, step]) |
返回一個(gè)表示由 range(start, stop, step)
所指定索引集的 slice 對象。 其中 start 和 step 參數(shù)默認(rèn)為 None
。 切片對象具有僅會(huì)返回對應(yīng)參數(shù)值(或其默認(rèn)值)的只讀數(shù)據(jù)屬性 start
, stop
和 step
。 它們沒有其他的顯式功能;不過它們會(huì)被 NumPy 以及其他第三方擴(kuò)展所使用。
切片對象也會(huì)在使用擴(kuò)展索引語法時(shí)被生成。 例如: a[start:stop:step]
或 a[start:stop, i]
。
請參閱 itertools.islice() 了解返回迭代器的一種替代版本。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
items = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] a = slice ( 2 , 4 ) print (items[ 2 : 4 ]) # [2, 3] items[a] # [2:3] items[a] = [ 10 , 11 ] print (items) # [0, 1, 10, 11, 4, 5, 6] del items[a] # [0, 1, 4, 5, 6] |
如果有一個(gè)slice對象的實(shí)例s,可以分別通過s.atart、s.stop以及s.step屬性來得到關(guān)于該對象的信息。例:
1
2
3
4
5
6
7
|
a = slice ( 10 , 50 , 2 ) print (a.start) # 10 print (a.stop) # 50 print (a.step) # 2 |
下面是indices官方解釋:
slice.
indices
(self, length)
此方法接受一個(gè)整型參數(shù) length 并計(jì)算在切片對象被應(yīng)用到 length 指定長度的條目序列時(shí)切片的相關(guān)信息應(yīng)如何描述。其返回值為三個(gè)整型數(shù)組成的元組;這些數(shù)分別為切片的 start 和 stop 索引號(hào)以及 step 步長值。索引號(hào)缺失或越界則按照正規(guī)連續(xù)切片的方式處理。
所有的值都已經(jīng)恰當(dāng)?shù)南拗圃谶吔缫詢?nèi)(當(dāng)做索引操作時(shí)可避免出現(xiàn)IndexError異常)例:
1
2
3
4
5
6
7
8
|
s = 'HelloWorld' a.indices( len (s)) # (5, 10, 2) for i in range ( * a.indices( len (s))): print (s[i]) # w # r # d |
以上就是詳解python編程slice與indices使用示例的詳細(xì)內(nèi)容,更多關(guān)于python編程slice與indices的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://blog.csdn.net/chenyuhuaxin/article/details/100565816