【发布时间】:2012-12-01 01:46:17
【问题描述】:
我正在使用 Python 3.3。我想得到一个slice 对象并用它来创建一个新的range 对象。
是这样的:
>>> class A:
def __getitem__(self, item):
if isinstance(item, slice):
return list(range(item.start, item.stop, item.step))
>>> a = A()
>>> a[1:5:2] # works fine
[1, 3]
>>> a[1:5] # won't work :(
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
a[1:5] # won't work :(
File "<pyshell#9>", line 4, in __getitem__
return list(range(item.start, item.stop, item.step))
TypeError: 'NoneType' object cannot be interpreted as an integer
好吧,这里的问题很明显 - range 不接受 None 作为值:
>>> range(1, 5, None)
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
range(1, 5, None)
TypeError: 'NoneType' object cannot be interpreted as an integer
但是(对我而言)不明显的是解决方案。我将如何打电话给range,以便在任何情况下都能正常工作?
我正在寻找一种不错的 Pythonic 方法。
【问题讨论】:
-
在 Python 3 中您可以切片
range对象以获得新的range对象是否有帮助? -
对于那些正在寻找一个简单和更一般的答案的人,来自Labrys Knossos 的答案如下:
range(item.start or 0, item.stop or len(self), item.step or 1)。如果不在定义了__len__的类中,则根据需要替换len(self)。
标签: python python-3.x range slice