2

我想要从索引 4 开始到 9 的数组。我对为 < 4 创建内存空间不感兴趣,那么最好如何进行?我的二维码如下:

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。这可能很明显,但有没有办法做到这一点?

感谢您对 dicts 的建议,我一直在避免这些 - 我知道 - 我正在转换的大部分代码都来自 C,但我认为字典可能是救世主。有没有办法用数组做我要求的事情?

4

4 回答 4

2

您可以简单地模拟一个列表:

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
于 2011-10-21T11:43:49.593 回答
2

对于稀疏数组,请使用dict

sparseArray = {}
sparseArray[(0,0)] = 1
sparseArray[(128,128)] = 1

print sparseArray # Show the content of the sparse array
print sparseArray.keys() # Get all used indices.
于 2011-10-21T11:37:09.433 回答
0

您在这里有两个选择。你可以使用稀疏列表,或者你可以创建一个容器类型,它基本上有一个普通列表和一个起始索引,这样当你请求时

specialist.get(4)

你实际上得到

specialist.innerlist[4 - startidx]
于 2011-10-21T11:40:49.857 回答
0

如果你真的想要列表语义和所有,我想你可以做

class OffsetyList(list):
    def __init__(self, *args, **kwargs):
        list.__init__(self, *args)
        self._offset = int(kwargs.get("offset", 0))

    def __getitem__(self, idx):
        return list.__getitem__(self, idx + self._offset)

    def __setitem__(self, idx, value):
        list.__setitem__(self, idx + self._offset, value)

    # Implementing the rest of the class
    # is left as an exercise for the reader.

ol = OffsetyList(offset = -5)
ol.extend(("foo", "bar", "baz"))
print ol[5], ol[7], ol[6]

但这至少可以说是非常脆弱的。

于 2011-10-21T11:47:28.483 回答