2

インデックス 4 から始まり 9 までの配列が必要です。4 未満のメモリ空間を作成することに興味がないので、どのように進めるのが最善でしょうか? 私の2Dコードは次のとおりです。

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

特定の範囲、つまり最後のインデックスが 0 から 127 ではなく 1 から 128 までを選択的に使用するにはどうすればよいでしょうか。これは明白かもしれませんが、これを行う方法はありますか?

辞書の提案をありがとう、私はこれらを避けてきました-私が知っている-私が変換しているコードの多くは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

ここには 2 つのオプションがあります。スパース リストを使用するか、基本的に通常のリストと開始インデックスを持つコンテナ タイプを作成して、リクエストしたときに

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 に答える