簡體   English   中英

在 Python 中使用字符串作為切片索引? (類型錯誤:切片索引必須是整數或無或具有 __index__ 方法)

[英]Use strings as slice indices in Python ? (TypeError: slice indices must be integers or None or have an __index__ method)

我有一個排序數組:

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 ( [) ) 行為。

另請注意,我僅實現了字符串切片用例。 您可以根據需要實施其他用例和錯誤處理。

我還使用 numpy 通過二分搜索發布了我的解決方案

class Stock():

    def __init__(self, name, date):
        self.name = name
        self.date = np.array(date)


    def __getitem__(self, key):

        if isinstance(key, slice):
            if key.start is not None and key.stop is not None: 
                return self.date[np.searchsorted(self.date, key.start, side='left', sorter=None):np.searchsorted(self.date, key.stop, side='left', sorter=None)]
            elif key.start is not None:
                return self.date[np.searchsorted(self.date, key.start, side='left', sorter=None):]
            elif key.stop is not None:
                return self.date[:np.searchsorted(self.date, key.stop, side='left', sorter=None)]
            else:
                return self.date[:]

        i = np.searchsorted(self.date, key, side='left', sorter=None)
        if key != self.date[i]:
            raise KeyError('key: {} was not found!'.format(key))
        else:
            return self.date[i]



aapl = Stock('aapl', ['2010','2012', '2014', '2016', '2018'])

print(aapl['2011':])
print(aapl['2014':'2017'])
print(aapl[:'2016'])
print(aapl['2010'])
print(aapl['2013'])

'''
['2012' '2014' '2016' '2018']
['2014' '2016']
['2010' '2012' '2014']
2010
Traceback (most recent call last):
  File "C:\Users\...\Desktop\...\stock.py", line ##, in <module>
    print(aapl['2013'])
  File "C:\Users\...\Desktop\...\stock.py", line ##, in __getitem__
    raise KeyError('key: {} was not found!'.format(key))
KeyError: 'key: 2013 was not found!'
'''

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM