Python slice how-to,我知道Python slice,但是如何使用内置的slice对象呢?

2024-05-17 03:21:38 发布

您现在位置:Python中文网/ 问答频道 /正文

内置函数slice的用途是什么,我如何使用它?
我知道Python切片的直接方法-l1[start:stop:step]。我想知道我是否有一个切片对象,那么如何使用它?


Tags: 对象方法函数l1step切片slice用途
3条回答

序列后面的方括号表示索引或切片,具体取决于括号内的内容:

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

这两种情况都由序列的__getitem__()方法(如果在等号的左边,则为__setitem__())处理。索引或切片作为单个参数传递给方法,Python的方法是将切片符号(在本例中为1:10:2)转换为切片对象:slice(1,10,2)

因此,如果要定义自己的序列类,或者重写另一个类的__getitem____setitem__、或__delitem__方法,则需要测试索引参数,以确定它是int还是slice,并相应地处理:

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)

通过调用slice创建一个slice,使用的字段与执行[start:end:step]表示法时使用的字段相同:

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
>>> 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)),)
>>>

相关问题 更多 >