我正在通过OReilly Technical School上课,其任务是将2-d array class
与列表implementation
一起调整为3-d array class
。
这是我的改编:
import array as sys_array
class array:
def __init__(self, M, N, O):
"Create 3-D array of lists stuffed with zeroes"
self._data = sys_array.array("i", [0] * M * N * O)
self._rows = M
self._cols = N
self._depth = O
def __getitem__(self, key):
"returns the appropriate element for a three-element tuple subscript tuple."
row, col, depth = self._validate_key(key)
return self._data[row*self._cols+col*self._depth+depth]
def __setitem__(self, key, value):
"sets the appropriate element for a three-element subscript tuple."
row, col, depth = self._validate_key(key)
self._data[row*self._cols+col*self._depth+depth] = value
def _validate_key(self, key):
"""Validates a key against the array's shape, returning good tuples.
Raises KeyError on problems."""
row, col, depth = key
if (0 <= row < self._rows and 0 <= col < self._cols and 0 <= depth < self._depth):
return key
raise KeyError("subscript out of range")
当我使用以下代码测试它时,我遇到了问题,我怀疑是def __init__(self, M, N, O):
"Create 3-D array of lists stuffed with zeroes"
self._data = sys_array.array("i", [0] * M * N * O)
self._rows = M
self._cols = N
self._depth = O
def __getitem__(self, key):
"returns the appropriate element for a three-element tuple subscript tuple."
row, col, depth = self._validate_key(key)
return self._data[row*self._cols+col*self._depth+depth]
def __setitem__(self, key, value):
"sets the appropriate element for a three-element subscript tuple."
row, col, depth = self._validate_key(key)
self._data[row*self._cols+col*self._depth+depth] = value
def _validate_key(self, key):
"""Validates a key against the array's shape, returning good tuples.
Raises KeyError on problems."""
row, col, depth = key
if (0 <= row < self._rows and 0 <= col < self._cols and 0 <= depth < self._depth):
return key
raise KeyError("subscript out of range")
和getitem
语句,特别是
setitem
索引短语,但如果有的话我在这里没有看到问题。这是测试代码和问题:
self._data[row*self._cols+col*self._depth+depth]
我不应该得到任何&#34;掷骰子!&#34;但是我愿意。谁能帮我看看我错过了什么?
谢谢! 戴夫
答案 0 :(得分:0)
在计算数组索引时需要考虑_depth。
def __getitem__(self, key):
"returns the appropriate element for a three-element tuple subscript tuple."
row, col, depth = self._validate_key(key)
return self._data[row*self._cols*self._depth + col*self._depth + depth]
def __setitem__(self, key, value):
"sets the appropriate element for a three-element subscript tuple."
print(key)
row, col, depth = self._validate_key(key)
self._data[row*self._cols*self._depth + col*self._depth + depth] = value
以防万一:用于调试的print语句:
def __str__(self):
'''
'''
ret = ''
for row in range(self._rows):
for col in range(self._cols):
for depth in range(self._depth):
print(row, col, depth)
ret += '{} '.format(self[row, col, depth])
ret += '\n'
ret += '\n'
return ret