我有一个排序数组:
arr = ['Alexander', 'Belman', 'Erik', 'Nicholas', ... , 'Zahir']
我想做这样的事情:
arr['B':'M'] # ['Belman', 'Erik']
如何创建类并实现
__getitem__
__index__
以正确的方式实现这一目标?
我正在考虑使用类似的东西
def __getitem__(self, key):
if isinstance(key, slice):
return [self.list[i] for i in range(key.start, key.stop)]
return self.list[key]
但我不知道如何为字符串编制索引。我如何创建一个
__index__
将二进制搜索应用于self.list
并返回正确索引的方法?
我认为您可以采用以下简单的实现方法:
from collections import UserList
class MyList(UserList):
def __getitem__(self, key):
if isinstance(key, slice):
return [e for e in self.data if key.start <= e < key.stop]
# TODO implement the rest of the usecases and/or error handling...
# for now slicing with integers will miserably fail,
# and basic integer indexing returns None
arr = MyList(['Alexander', 'Belman', 'Erik', 'Nicholas', 'Zahir'])
print(arr['B':'M'])
将输出
['Belman', 'Erik']
同样,
print(arr['Alex':'Er'])
将输出
['Alexander', 'Belman']
请注意,我使用key.start <= e < key.stop
与整个python中使用的inclusive:exclusive([)
)行为保持一致。
还要注意,我仅实现了字符串切片用例。您可以根据需要实施其他用例和错误处理。