使用字符串作为Python中的切片索引?(TypeError:切片索引必须为整数或无,或具有__index__方法)

用户名

我有一个排序数组:

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__

将binarySearch应用于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()行为保持一致。

还要注意,我仅实现了字符串切片用例。您可以根据需要实施其他用例和错误处理。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档