NAS*_*ern 10 python data-structures
我有一个奇怪的问题:我有64个数字的列表永远不会改变:
(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128)
Run Code Online (Sandbox Code Playgroud)
我需要一个Python数据结构,这将允许我使用1-64索引而不是标准0-63来获取这些数字.这可能吗?完成此任务的最佳方法是建立字典吗?
Joe*_*ett 40
只需0在结构的开头插入一个:
(0, 2, 4, 6, 8, ...)
Run Code Online (Sandbox Code Playgroud)
您可以覆盖项目getter并创建一个专门的元组:
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
Run Code Online (Sandbox Code Playgroud)