你想要一个
slice() object:
index = slice(0, 2)
print(somelist[index])
slice()模拟您可以在[start:stop:stride]预订语法中指定的start,stop和stride值作为对象.
从文档:
Return a 07001 object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default).
在幕后,Python实际上在调用自定义__getitem__方法时将订阅转换为slice()对象:
>>> class Foo(object):
... def __getitem__(self, item):
... return item
...
>>> Foo()[42:81:7]
slice(42, 81, 7)
>>> Foo()[:42]
slice(None, 42, None)
一个可行的替代方案是将start和stop存储为单独的值:
startindex = 0
stopindex = 2
print(somelist[start:stop])