[英]Periodic List in Python
我正在尝试在Python中创建一个循环列表。 即,如果x
> len(list)
,则list[x]
等于list[x - len(list)]
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
谁能告诉我我做错了什么?
您有一个错误的错误。 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
回想一下列表索引是从0开始的; 因此,您需要while (idx >= len(self)):
很好的测试用例!
问题是您的状况:
while (idx > len(self)): idx -= len(self)
您应该将其替换为:
while (idx >= len(self)): idx -= len(self)
尽管这远非有效。 一种更有效的方法是使用模( %
):
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.