Python制作循环列表以超出范围索引 [英] Python make a circular list to get out of range index
问题描述
我正在寻找使列表成为循环列表的方法,以便可以呼叫索引超出范围的数字.
I'm looking for ways to make a list into circular list so that I can call a number with index out of range.
例如,我目前有这个课程:
For example, I currently have this class:
class myClass(list):
definitely __init__(self, *x):
super().__init__(x)
用作:
>> myList = myClass(1,2,3,4,5,6,7,8,9,10)
>> print(myList)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
在创建列表后,我想要:
and after creating a list, I want to:
>> myList[2]
3
>> myList[12]
3
>> myList[302]
3
>> myList[-1]
10
>> myList[-21]
10
...
目前,无法使用索引[12],[302]和[-21],因为它超出了单个列表的范围,因此,如果索引超出范围,我想制作一个循环列表然后将它们变为可能.
At the moment, index [12], [302] and [-21] are not possible since it is out of range for a single list, so I want to make a circular list if the index is out of range which will then make them possible.
- myList [12] = 3,因为循环列表将是[1、2、3、4、5、6、7、8、9、10、1、2、3、4、5、6、7,8、9、10 ...].
- 该列表仅由5或10个数字组成.
推荐答案
如果您坚持为此创建整个类,请为 UserList
子类,实现 __ getitem __
并使用取模运算符(%
),其长度为列表:
If you insist on creating an entire class for this, subclass UserList
, implement __getitem__
and use the modulo operator (%
) with the length of the list:
class myClass(UserList):
def __getitem__(self, item):
return super().__getitem__(item % len(self))
myList = myClass([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(myList[12])
输出
3
根据您的用法,可能需要实现其他几种 list
方法.
Depending on your usage, it's possible you'll need to implement several other list
methods.
注意::请注意不要循环播放 myList
.这将创建一个无限循环,因为 __ getitem __
将始终能够提供列表中的元素.
CAVEAT: Be careful to not loop over myList
. That will create an infinite loop because __getitem__
will always be able to provide an element from the list.
这篇关于Python制作循环列表以超出范围索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!