2010-10-12 50 views

回答

72

通過調用片具有相同的字段創建片,如果這樣做,你會使用[開始:結束:步]符號:

sl = slice(0,4) 

要使用切片,只是把它當作好像它是指數成列表或字符串:

>>> s = "ABCDEFGHIJKL" 
>>> sl = slice(0,4) 
>>> print(s[sl]) 
'ABCD' 

假設您有一個固定長度文本字段的文件。您可以定義切片列表,以便輕鬆從該文件中的每個「記錄」中提取值。

data = """\ 
0010GEORGE JETSON 12345 SPACESHIP ST HOUSTON  TX 
0020WILE E COYOTE 312 ACME BLVD  TUCSON  AZ 
0030FRED FLINTSTONE 246 GRANITE LANE  BEDROCK  CA 
0040JONNY QUEST  31416 SCIENCE AVE PALO ALTO  CA""".splitlines() 


fieldslices = [slice(*fielddef) for fielddef in [ 
    (0,4), (4, 21), (21,42), (42,56), (56,58), 
    ]] 
fields = "id name address city state".split() 

for rec in data: 
    for field,sl in zip(fields, fieldslices): 
     print("{} : {}".format(field, rec[sl])) 
    print('') 

打印:

id : 0010 
name : GEORGE JETSON  
address : 12345 SPACESHIP ST 
city : HOUSTON  
state : TX 

id : 0020 
name : WILE E COYOTE  
address : 312 ACME BLVD   
city : TUCSON   
state : AZ 

id : 0030 
name : FRED FLINTSTONE 
address : 246 GRANITE LANE  
city : BEDROCK  
state : CA 

id : 0040 
name : JONNY QUEST  
address : 31416 SCIENCE AVE  
city : PALO ALTO  
state : CA 
3

slice函數返回slice objects。 Slice對象是Python的內部類型之一,它爲讀取性能進行了優化 - 它們的所有屬性都是隻讀的。

如果希望更改默認行爲,則更改slice可能會很有用。例如,lxml使用切片符號來訪問DOM元素(但是,我還沒有確認他們是如何做到這一點的)。

28

下一個序列方括號表示無論是索引或切片取決於括號裏面是什麼:

>>> "Python rocks"[1] # index 
'y' 
>>> "Python rocks"[1:10:2] # slice 
'yhnrc' 

這些情況都被__getitem__()方法處理(或__setitem__(),如果在等號左邊)。索引或切片作爲單個參數傳遞給方法,並且t他這樣做的方式是通過將切片符號(在本例中爲1:10:2)轉換爲切片對象:slice(1,10,2)

所以,如果你要定義自己的序列狀類或覆蓋另一個類的__getitem____setitem____delitem__方法,你需要測試的指標參數來確定它是否是相應的intslice和過程:

def __getitem__(self, index): 
    if isinstance(index, int): 
     ... # process index as an integer 
    elif isinstance(index, slice): 
     start, stop, step = index.indices(len(self)) # index is a slice 
     ... # process slice 
    else: 
     raise TypeError("index must be int or slice") 

slice對象有三個屬性:startstopstep,和一個方法:indices,這需要一個參數,該對象的長度,並返回一個3元組:(start, stop, step)

5
>>> class sl: 
... def __getitem__(self, *keys): print keys 
...  
>>> s = sl() 
>>> s[1:3:5] 
(slice(1, 3, 5),) 
>>> s[1:2:3, 1, 4:5] 
((slice(1, 2, 3), 1, slice(4, 5, None)),) 
>>> 
+2

請參閱Don的回覆以獲取解釋。 – abc 2013-02-02 01:51:45

+0

這也是有益的,也指出可以有多個切片傳遞給'__getitem__':s [1:2:3,1:4:5] =>(切片(1,2,3),1 ,切片(4,5,無))'。 – OozeMeister 2017-11-04 21:55:56