固定数组索引在Python [英] Fixing array indices in Python
问题描述
我想有发言权,从4索引启动阵列和去9.我不感兴趣,在与LT建立内存空间; 4,如何最好继续吗?我的2D code是如下:
I'd like to have arrays that start from say an index of 4 and go to 9. I'm not interested in creating memory space for < 4, so how is best to proceed? My 2D code is as follows:
arr = [[ 0 for row in range(2)] for col in range(1, 129)]
>>> arr[0][0] = 1
>>> arr[128][0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
>>> arr[127][0] = 1
如何选择只使用特定范围,即其中最后一个指数从1到128(含)不为0到127这可能是显而易见的,但有没有办法做到这一点?
How can selectively just use the specific range i.e. where the last index runs from 1 to 128 inclusive not 0 to 127. This maybe obvious, but is there a way to do this?
感谢您的建议的类型的字典,我一直避免这些 - 我知道 - 大部分code,我转换的是C,但我认为可能的字典的救星。有没有办法做什么,我使用数组问?
Thanks for the suggestion for dicts, I have been avoiding these - I know - much of the code I'm converting is from C, but I think dictionaries might the saviour. Is there a way to do what I am asking with arrays?
推荐答案
您可以简单的模拟列表:
class OffsetList(object):
def __init__(self, offset=4):
self._offset = offset
self._lst = []
def __len__(self):
return len(self._lst)
def __getitem__(self, key):
return self._lst[key - self._offset]
def __setitem__(self, key, val):
self._lst[key - self._offset] = val
def __delitem__(self, key):
del self._lst[key - self._offset]
def __iter__(self):
return iter(self._lst)
def __contains__(self, item):
return item in self._lst
# All other methods go to the backing list.
def __getattr__(self, a):
return getattr(self._lst, a)
# Test it like this:
ol = OffsetList(4)
ol.append(2)
assert ol[4] == 2
assert len(ol) == 1
这篇关于固定数组索引在Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!