Python切片操作方法,我知道Python切片但是如何使用内置切片对象呢?

nec*_*cer 64 python slice

内置函数的slice用途是什么?如何使用它?
我知道Pythonic切片的直接方式 - l1[start:stop:step].我想知道我是否有切片对象,那我该如何使用呢?

Pau*_*McG 89

您可以通过调用切片来创建切片,并使用与[start:end:step]表示法相同的字段:

sl = slice(0,4)
Run Code Online (Sandbox Code Playgroud)

要使用切片,只需将其作为索引传递给列表或字符串:

>>> s = "ABCDEFGHIJKL"
>>> sl = slice(0,4)
>>> print(s[sl])
'ABCD'
Run Code Online (Sandbox Code Playgroud)

假设您有一个固定长度文本字段的文件.您可以定义切片列表,以便轻松地从此文件中的每个"记录"中提取值.

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('')
Run Code Online (Sandbox Code Playgroud)

打印:

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
Run Code Online (Sandbox Code Playgroud)


Don*_*ell 33

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

>>> "Python rocks"[1]    # index
'y'
>>> "Python rocks"[1:10:2]    # slice
'yhnrc'
Run Code Online (Sandbox Code Playgroud)

这两种情况都是由__getitem__()序列的方法处理的(或者__setitem__()如果在等号的左边.)索引或切片作为单个参数传递给方法,Python的方式是通过转换切片表示法,(1:10:2在这种情况下)切片对象:slice(1,10,2).

因此,如果要定义自己的类序列或重写另一个类的__getitem__or __setitem____delitem__方法,则需要测试index参数以确定它是a int还是a 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")
Run Code Online (Sandbox Code Playgroud)

slice对象有三个属性:start,stopstep,和一个方法:indices,其中只有一个参数,该对象的长度,并返回一个3元组:(start, stop, step).


Sin*_*ion 7

>>> 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)),)
>>>
Run Code Online (Sandbox Code Playgroud)

  • 请参阅下面的Don的回复,了解为何会发生这种情况. (2认同)