標籤:tor turn nta iter 對象 present property util hat
官方文檔
-
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) | Return repr(self). | | indices(...) | S.indices(len) -> (start, stop, stride) | | Assuming a sequence of length len, calculate the start and stop | indices, and the stride length of the extended slice described by | S. Out of bounds indices are clipped in a manner consistent with the | handling of normal slices. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | start | | step | | stop | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
li = [11,22,33,44,55,66,77]ret1 = li[None:5:None] #start,stem為Noneret2 = li[:5:] #同上print(ret1,ret2)#輸出#[11, 22, 33, 44, 55] [11, 22, 33, 44, 55]ret3 = li[2:5:None] #step為Noneret4 = li[2:5:]print(ret3,ret4) #同上#輸出#[33, 44, 55]#[33, 44, 55]ret5 = li[1:6:3]print(ret5)#輸出#[22, 55]
3.對應切片的3個屬性start、stop、step,slice函數也有3個對應的參數start、stop、step,其值會直接賦給切片對象的start、stop、step
#定義c1c1 = slice(5)print(c1)#輸出#slice(None, 5, None)#定義c2c2 = slice(2,5)print(c2)#輸出#slice(2, 5, None)#定義c3c3 = slice(1,6,3)print(c3)#輸出#slice(1, 6, 3)a = list(range(1,10))ret1 = a[c1] #同a[:5:]一樣print(ret1)#輸出#[1, 2, 3, 4, 5]ret2 = a[c2] #同a[2:5:]一樣print(ret2)#輸出#[3, 4, 5]ret3 = a[c3] #同a[1:6:3]一樣print(ret3)#輸出#[2, 5]
Python內建函數(19)-slice