2D arrays with array module #11611
-
Can array module be used for creating 2D arrays? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 6 replies
-
No, only 1 D array , but it is possible to create serialized (class) array and dedicated 2d array operations . |
Beta Was this translation helpful? Give feedback.
-
This example shows how the grid = Grid(args) # Args include no. of rows and cols
grid[[5, 8]] = 42
value = grid[[11, 12]] In this instance the object being accessed is a list ( The application does not require high performance. |
Beta Was this translation helpful? Give feedback.
-
Note |
Beta Was this translation helpful? Give feedback.
-
@peterhinch with Your code I got (esp32/MicroPython v1.19.1) : Traceback (most recent call last):
File "<stdin>", line 392, in <module>
TypeError: function takes 3 positional arguments but 2 were given edit: ~~So it looks like a setitem with 3 argument have something with that ? ~~ -> for I solved problem just passing arguments with *args: class Array2D:
def __init__(self, nrows, ncols):
self._buf = array.array("I", (0 for _ in range(nrows*ncols)))
self._ncols = ncols
self._nrows = nrows
def __getitem__(self, *args):
row, col = args[0][0], args[0][1]
return self._buf[col + row * self._ncols]
def __setitem__(self,*args):
row, col, value = args[0][0], args[0][1] , args[1]
self._buf[col + row * self._ncols] = value
arr = Array2D(4, 4)
arr[0,0]=0
arr[0,1]=1
arr[0,2]=2
arr[0,3]=3
arr[1,0]=4
arr[1,1]=5
print(arr[0,0])
print(arr[1,0])
print(arr._buf) |
Beta Was this translation helpful? Give feedback.
-
For anyone coming across this thread I have written a generator function. This allows a generator to iterate over indices created with 1D or 2D array syntax, including 2- or 3- arg slices. This simplifies creating classes which accept 2D array syntax, for example: def __getitem__(self, *args):
indices = do_args(args, self.nrows, self.ncols) # Create a generator
for i in indices:
yield self.cells[i] # Iterate over specified cells |
Beta Was this translation helpful? Give feedback.
if You mean:
x[0]
-> get row 0 , andx[0:1]
-> get slice of row 0 from index 0 to 1 then ingetitem You need add
isinstance(args[0], tuple)
checking first, and thenisinstance(args[0][1] , slice)
and isinstance(args[0][1] , slice) for recognition what way you going to get values.edit (something like that):