Skip to content
Advertisement

Putting serial values in a matrix with Python

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):

data_matrix = [ [] , [] ]
while (elem = new_element_available()):
    data_matrix[ elem[x] ][ elem[y] ] = elem[val]

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.

inp = [(0, 0, 0), (0, 2, 1), (1, 1, 2), (3, 3, 3)]

outp = []
for x, y, val in inp:
    outp.extend([] for _ in range(x-len(outp)+1))
    outp[x].extend(None for _ in range(y-len(outp[x])+1))
    outp[x][y] = val

print(outp)

[[0, None, 1], [None, 2], [], [None, None, None, 3]]

Alternatively you can use a dictionary-based structure with defaultdict:

import collections
outp = collections.defaultdict(dict)
for x, y, val in inp:
    outp[x][y] = val

print(dict(outp))

{0: {0: 0, 2: 1, 1: 4}, 1: {1: 2}, 3: {3: 3}}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement