Python Data structure index Start at 1 instead of 0?

前端 未结 4 746
说谎
说谎 2020-12-19 02:06

I have a weird question: I have this list of 64 numbers that will never change:

(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,          


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-19 02:50

    You could override the item getter and make a specialized tuple:

    class BaseOneTuple(tuple):
        __slots__ = () # Space optimization, see: http://stackoverflow.com/questions/472000/python-slots 
        def __new__(cls, *items):
            return tuple.__new__(cls, items) # Creates new instance of tuple
        def __getitem__(self, n):
            return tuple.__getitem__(self, n - 1)
    
    
    b = BaseOneTuple(*range(2, 129, 2))
    b[2] == 4
    

提交回复
热议问题