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

JavaScript

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

JavaScript

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

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement