Python中的周期列表

时间:2016-06-08 12:34:25

标签: python list

我正在尝试在Python中创建循环列表。即,如果list[x]> list[x - len(list)]等于x的列表。 len(list)

以下是代码:

class Circ(list):
    def __getitem__(self, idx):
        while (idx > len(self)):
            idx -= len(self)
        return super(Circ, self).__getitem__(idx)

但是,我仍然从以下代码中收到错误:

c = Circ([1,2,3])
c[3]
>> IndexError: list index out of range

有谁可以告诉我我做错了什么?

3 个答案:

答案 0 :(得分:4)

您有一个错误的错误。 Python列表索引从开始,因此有效索引为0,1和2.因为3等于len(self),所以你永远不会减少它。

测试idx是否大于或等于长度:

while idx >= len(self):
    idx -= len(self)

或简单地使用%模数运算符:

return super(Circ, self).__getitem__(idx % len(self))

演示:

>>> class Circ(list):
...     def __getitem__(self, idx):
...         return super(Circ, self).__getitem__(idx % len(self))
...
>>> c = Circ([1, 2, 3])
>>> c[3]
1

答案 1 :(得分:0)

回想一下,列表索引是基于0的;因此,你想要while (idx >= len(self)):

好的测试用例!

答案 2 :(得分:0)

问题在于你的条件:

while (idx > len(self)):
    idx -= len(self)

您应该将其替换为:

while (idx >= len(self)):
    idx -= len(self)

虽然这远远没有效率。更有效的方法是使用modulo(%):

def __getitem__(self, idx):
    return super(Circ, self).__getitem__(idx%len(self))

模数在除法后计算(正)余数(尽管如果除法器为负,模数也为负)。例如:

>>> 2%4
2
>>> 3%4
3
>>> 4%4
0
>>> 5%4
1
>>> -5%4
3