python中index、slice與slice assignment用法
一、index與slice的定義:
- index用於枚舉list中的元素(Indexes enumerate the elements);
- slice用於枚舉list中元素集合(Slices enumerate the spaces between the elements).
- slice assignment,是一個語法糖,主要用於list的快速插入、替換、刪除元素。
二、語法
index
index語法很簡單,如下表所示,如有一個list a,a[i]表示a中第i個元素(a[0]表示第一個元素),當i<0時,表示倒數第幾個元素(a[-1]表示倒數第一個元素)。
Python indexes and slices for a six-element list.
Indexes enumerate the elements, slices enumerate the spaces between the elements.
Index from rear: -6 -5 -4 -3 -2 -1 a=[0,1,2,3,4,5] a[1:]==[1,2,3,4,5]
Index from front: 0 1 2 3 4 5 len(a)==6 a[:5]==[0,1,2,3,4]
+---+---+---+---+---+---+ a[0]==0 a[:-2]==[0,1,2,3]
| a | b | c | d | e | f | a[5]==5 a[1:2]==[1]
+---+---+---+---+---+---+ a[-1]==5 a[1:-1]==[1,2,3,4]
Slice from front: : 1 2 3 4 5 : a[-2]==4
Slice from rear: : -5 -4 -3 -2 -1 :
b=a[:]
b==[0,1,2,3,4,5] (shallow copy of a)
slice
slice的基本形式為a[start : end : step],這三個參數都有默認的缺省值,但是為了與index區別,slice語法中至少要有一個:
,對缺省值的理解是正確使用slice的關鍵,可以用一下幾條來說明:
-
step的默認值為1,若step > 0表示從前向后枚舉,step < 0則相反,step不能為0;
-
start、end的默認值與step值的正負相關,可見下表:
------------------------- step | + | - | ------------------------- start | 0 | -1 | end | len | -(len+1)| -------------------------
-
step和end中的負值都可以通過加上len得到其正值,有別於range(start,end)。
slice assignment
a[start : end : step] = b與b = a[start : end : step]不同,后者是在list a中取出一些元素,然后重新組成一個新的list給b,不會改變list a的值;而前者直接改變a的值。其主要用法有:
- 插入
>>> a = [1, 2, 3]
>>> a[0:0] = [-3, -2, -1, 0]
>>> a
[-3, -2, -1, 0, 1, 2, 3]
- 刪除
>>> a
[-3, -2, -1, 0, 1, 2, 3]
>>> a[2:4] = []
>>> a
[-3, -2, 1, 2, 3]
- 替換
>>> a
[-3, -2, 1, 2, 3]
>>> a[:] = [1, 2, 3]
>>> a
[1, 2, 3]
引用:
--http://stackoverflow.com/questions/509211/explain-pythons-slice-notation