如何在python3中实现slice?

2024-09-26 18:17:22 发布

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

我在python3中读到了关于slice的文章。然后我编写了一个程序,试图实现__getitem__(self, slice(s))。代码如下:

class NewList:
    def __init__(self, lst):
        print('new list')
        self._list = lst
    def __getitem__(self, x):
        if type(x) is slice:
            return [ self._list[n] for n in range(x.start, x.stop, x.step) ]  #error?
        else:
            return self._list[x]
    ...

nl1 = NewList([1,2,3,4,5])
nl1[1:3]  #error occurs

然后我发现x.step是{},这使得range raise成为一个异常。 那么,我应该如何实现__getitem__方法呢?在


Tags: self程序returndefstep文章slicerange
3条回答

在不知道对象长度的情况下,有一个明显的技巧可以绕过这个强制参数。例如,无限序列的getitem可以如下所示:

  def __getitem__( self, key ) :
    if isinstance( key, slice ) :
       m = max(key.start, key.stop)
       return [self[ii] for ii in xrange(*key.indices(m+1))]
    elif isinstance( key, int ) :
       #Handle int indices

它只会失败,如果你不给启动和停止,但没有检查,这也可以处理。在

如果x是一个切片,则可以执行与其他条件相同的操作:

return self._list[x]

您需要使用slice.indices方法。给定序列的长度,它将返回start、stop、step的元组:

>>> s = slice(2, 5, None)
>>> s.indices(10)
(2, 5, 1)

>>> [x for x in range(*s.indices(10))]
[2, 3, 4]

>>> s.indices(3)
(2, 3, 1)

>>> s.indices(0)
(0, 0, 1)

相关问题 更多 >

    热门问题