gpt4 book ai didi

python - 在 Python 中使用字符串作为切片索引? (类型错误: slice indices must be integers or None or have an __index__ method)

转载 作者:行者123 更新时间:2023-12-02 03:26:44 24 4
gpt4 key购买 nike

我有一个排序数组:

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 中使用的包容:排他( [) )行为保持一致。

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

关于python - 在 Python 中使用字符串作为切片索引? (类型错误: slice indices must be integers or None or have an __index__ method),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59751964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com