I have a stream of elements that are coming serially: (x0, y0, val0), (x1, y2, val1), … (xN, yN, valN), etc.
x and y are the coordinates directly pointing where the val should be put in a matrix. I tried the following but it does not work (I expected the interpreter will automatically expand the matrix but it does not):
JavaScript
x
4
1
data_matrix = [ [] , [] ]
2
while (elem = new_element_available()):
3
data_matrix[ elem[x] ][ elem[y] ] = elem[val]
4
How can I do it in Python as similar as possible or at least – as easier as possible?
Advertisement
Answer
Extend your array to accommodate incoming points as you go. You may end up with a jagged 2D array, but you should be able to square it up easily if you need to.
JavaScript
1
10
10
1
inp = [(0, 0, 0), (0, 2, 1), (1, 1, 2), (3, 3, 3)]
2
3
outp = []
4
for x, y, val in inp:
5
outp.extend([] for _ in range(x-len(outp)+1))
6
outp[x].extend(None for _ in range(y-len(outp[x])+1))
7
outp[x][y] = val
8
9
print(outp)
10
JavaScript
1
2
1
[[0, None, 1], [None, 2], [], [None, None, None, 3]]
2
Alternatively you can use a dictionary-based structure with defaultdict
:
JavaScript
1
7
1
import collections
2
outp = collections.defaultdict(dict)
3
for x, y, val in inp:
4
outp[x][y] = val
5
6
print(dict(outp))
7
JavaScript
1
2
1
{0: {0: 0, 2: 1, 1: 4}, 1: {1: 2}, 3: {3: 3}}
2