修复 Python 中的数组索引
我想要有从索引 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于稀疏数组,请使用
dict
:For sparse arrays, use a
dict
:您可以简单地模拟一个列表:
You can simply emulate a list:
这里你有两个选择。您可以使用稀疏列表,或者您可以创建一个基本上具有正常功能的容器类型列表和开始索引,这样当您请求时,
您实际上会得到
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
you actually get
如果您真的想要列表语义和所有内容,我想您可以做到,
但至少可以说这似乎非常脆弱。
If you really wanted list semantics and all, I suppose you could do
but this seems very fragile to say the least.