自定义包装器,用于索引从1开始的python列表 [英] Custom wrapper for indexing python list starting at 1

查看:98
本文介绍了自定义包装器,用于索引从1开始的python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为python list类型编写一个简单的包装程序,以强制它在1而不是0处开始索引.我有一个相当复杂的程序,它基于持续时间数据的某些离散概率分布,具有整数长度的存储桶,但是我的持续时间不小于1.无论如何,它将大大简化我的代码中的许多重要部分为了能够从1开始无缝索引.我最初使用的是dict,但是我发现它们的某些属性太麻烦了.

I'd like to write a simple wrapper for the python list type that forces it to start indexing at 1 instead of 0. I've got a a fairly complex program based on some discrete probability distributions of duration data, with integer-length buckets, but I don't have any durations of less than 1. Anyway, it would greatly simplify a some significant portions of my code to be able to seamlessly index starting at 1. I was using a dict at first but I found several properties of them to be too cumbersome.

我以前从未写过Python类的包装器,更不用说内置类型了,但是我觉得我想要做的事情很简单.至少,我应该能够做这样的事情:

I've never written a wrapper for a Python class before, much less a built-in type, but I feel like what I want to do is fairly simple. At the bare minimum, I should be able to do stuff like this:

>>> p = one_list([1,2,3,4,5])
>>> for i in range(1,6):
    print i, p[i]

1 1
2 2
3 3
4 4
5 5
>>> len(p)
5

但是,如果我也可以覆盖list类的其他一些相关的内置方法,例如index,则会很好.

However it would be good if I could overwrite some of the other relevant built-in methods of the list class as well, such as index.

>>> len(p)
5
>>> p.index(p[-1])
5

请分享您有关我可能如何做这样的事情的提示.我正在考虑是否只对自定义类执行此操作,但是这似乎太过分了.我也欢迎有关覆盖有用方法的任何建议.

Please share your tips as to how I might go about doing something like this. I was considering whether or not to just do it with a custom class, but that seems like it might be overkill. I also welcome any recommendations as to useful methods to overwrite.

后记

我只想指出这样做是不值得的,我接受以下答案的原因不是因为我试图按照他的描述来实施它,而是因为他帮助了我意识到列表本身就足够好.

I'd just like to note that it was not worth the trouble to do this, and the reason I've accepted the answer below is not because I tried to implement it in the way he describes, but because he helped me realize that lists are good enough on their own.

推荐答案

这是基于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...

这篇关于自定义包装器,用于索引从1开始的python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆