When working with a range of Python lists
int_list[10:2]
It is a slice object that is actually passed to the __get__ method, but when you try to implement a list class by yourself, it is a problem if you try to correspond to the slice argument. There is no method to convert slice to a column of index numbers.
It's hard to write such a conversion process on your own, if step is a negative number / None, if start or stop is a negative number / None, this will die in a storm of conditional branching.
However, there are methods that do such troublesome processing inconspicuously. It is slice.indices (). If you give the length of the list, it will normalize the negative number / None to a proper index number accordingly. With this, it's relatively easy to get a column of index numbers.
def iterate_by_slice(s: slice, length: int):
i, stop, step = s.indices(length)
if step > 0 :
while i < stop:
yield i
i += step
else:
while i > stop:
yield i
i += step
Please make more and more list-like classes that are useful to everyone.
Recommended Posts