问题
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)
which works as:
>> 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
...
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 because the circular list would be [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...].
- The list will be only made up with 5 or 10 numbers.
回答1:
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])
outputs
3
Depending on your usage, it's possible you'll need to implement several other list
methods.
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.
来源:https://stackoverflow.com/questions/61350386/python-make-a-circular-list-to-get-out-of-range-index