Search code examples
python-2.7tuplessparse-matrix

Python: turn tuples into array


Currently, I have a list of tuples that looks like this:

[(0, 0.13), (323, 0.72), (812, 0.35), ..., (2127, 0.44)]

The tuples are ordered by their first element: 0 -> 323 -> 812 -> ...

I want to turn this list of tuples into an array (or a sparse matrx), with the first element of each tuple being the second element's array index:

[0.13, 0, ..., 0, 0.72, 0, ...,  0, 0.35, 0, ...]

And to fill the end of this array with 0s to extend it into a certain length.

Can anyone provide a fast implementation of the function above in python?

I currently use a dictionary to accomplish this procedure, and it's very slow for large arrays.

Thank you.


Solution

  • You can preallocate an array of zeros and then fill in the supplied numbers:

    def expand_sparse_array(inp):
        length = (inp[-1][0]+1) # index of last element + 1
        out = [0]*length
    
        for (idx, val) in inp:
            out[idx] = val
    
        return out
    

    For example:

    >>> expand_sparse_array([(0, 0.13), (3, 0.72), (5, 0.35), (10, 0.44)])
    [0.13, 0, 0, 0.72, 0, 0.35, 0, 0, 0, 0, 0.44]