python中的数组与任意索引

vel*_*una 4 python arrays list

我是python的初学者.我想让任意索引的数组从pto 运行q,而不是从0运行.

如何创建一个q-p+1索引从?pq?的数组?

shx*_*hx2 6

您可以创建一个子类list来调整项访问的索引:

class ListWithOffset(list):
    def __init__(self, offset, *a, **kw):
        self.offset = offset
        super().__init__(*a, **kw)

    def __getitem__(self, i):
        return super().__getitem__(self, self._adjust_idx(i))

    def __setitem__(self, i, value):
        return super().__setitem__(self, self._adjust_idx(i), value)

    def __delitem__(self, i):
        return super().__delitem__(self, self._adjust_idx(i))

    def _adjust_idx(self, i):
        if isinstance(i, slice):
            return slice(i.start - self.offset if i.start is not None else None,
                         i.stop - self.offset if i.stop is not None else None,
                         i.step)
        else:
            return i - self.offset
Run Code Online (Sandbox Code Playgroud)

(编辑:忘了处理切片)

请注意,没有必要明确指定结束索引.它可以随着列表大小的变化而变化,并且可以mylist.offset + len(mylist)在任何时间点定义.

另请注意,我在此处以最简单的形式保留了代码段,但为了使其有用,您还需要处理传递的索引小于偏移量的情况.此实现可能会返回意外结果(对应于list访问负索引时的行为),这可能并不理想.