且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自定义包装器,用于索引从1开始的python列表

更新时间:2023-02-16 18:06:34

这是基于1的列表的完整(我认为)实现,可以正确处理切片(包括扩展切片),索引,弹出等操作.很难做到这一点超出您的想象,尤其是切片和负索引.实际上,我仍然不能100%地确定它是否可以正常工作,因此 caveat编码器.

Here's a complete (I think) implementation of a 1-based list, correctly handling slicing (including extended slices), indexing, popping, etc. It's slightly more tricky to get this right than you might think, especially the slicing and the negative indexes. In fact I'm still not 100% sure it works exactly as it should, so caveat coder.

class list1(list):
    """One-based version of list."""

    def _zerobased(self, i):
        if type(i) is slice:
            return slice(self._zerobased(i.start),
                         self._zerobased(i.stop), i.step)
        else:
            if i is None or i < 0:
                return i
            elif not i:
                raise IndexError("element 0 does not exist in 1-based list")
            return i - 1

    def __getitem__(self, i):
        return list.__getitem__(self, self._zerobased(i))

    def __setitem__(self, i, value):
        list.__setitem__(self, self._zerobased(i), value)

    def __delitem__(self, i):
        list.__delitem__(self, self._zerobased(i))

    def __getslice__(self, i, j):
        print i,j
        return list.__getslice__(self, self._zerobased(i or 1),
                                 self._zerobased(j))

    def __setslice__(self, i, j, value):
        list.__setslice__(self, self._zerobased(i or 1),
                          self._zerobased(j), value)

    def index(self, value, start=1, stop=-1):
        return list.index(self, value, self._zerobased(start),
                          self._zerobased(stop)) + 1

    def pop(self, i):
        return list.pop(self, self._zerobased(i))

不过,

senderle的ExtraItemList将具有更好的性能,因为它不需要不断地调整索引,也不需要在您和数据之间增加一层(非C!)方法调用.希望我会想到这种方法;也许我可以将它与我的结合起来...

senderle's ExtraItemList is going to have better performance, though, because it doesn't need to adjust the indices constantly nor does it have an extra layer of (non-C!) method calls between you and the data. Wish I'd thought of that approach; maybe I could profitably combine it with mine...