修复 Python 中的数组索引

发布于 2024-12-11 08:07:41 字数 522 浏览 0 评论 0原文

我想要有从索引 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(包括 1 到 128,而不是 0 到 127)。这可能是显而易见的,但有没有办法做到这一点?

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

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

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?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ヅ她的身影、若隐若现 2024-12-18 08:07:41

对于稀疏数组,请使用 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.

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.
清风无影 2024-12-18 08:07:41

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

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

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
但可醉心 2024-12-18 08:07:41

这里你有两个选择。您可以使用稀疏列表,或者您可以创建一个基本上具有正常功能的容器类型列表和开始索引,这样当您请求时,

specialist.get(4)

您实际上会得到

specialist.innerlist[4 - startidx]

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]
凉薄对峙 2024-12-18 08:07:41

如果您真的想要列表语义和所有内容,我想您可以做到,

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]

但至少可以说这似乎非常脆弱。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文