Fixing array indices in Python

不羁岁月 提交于 2019-12-06 07:22:06

For sparse arrays, use a 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.

You can simply emulate a list:

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
kojiro

You have two options here. You can use sparse lists, or you can create a container type that basically has a normal list and a start index, such that when you request

specialist.get(4)

you actually get

specialist.innerlist[4 - startidx]

If you really wanted list semantics and all, I suppose you could do

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]

but this seems very fragile to say the least.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!