1

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.

1
  • If I understand correctly, you want to create an array with 0 as placeholders for those indices that are missing; so between 0.13 and 0.72, there are 322 zeros - is that right? Commented Dec 31, 2015 at 5:38

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

I think this will do what you require:

results = []
for k,i in list_of_tuples:
  while k > len(results):
     results.append(0)
  results.append(i)

Here is a sample run, given an input of [(0, 12), (5, 43), (10, 1)], there result is:

>>> i = []
>>> for k,v in t:
...    while k > len(i):
...       i.append(0)
...    i.append(v)
...
>>> i
[12, 0, 0, 0, 0, 43, 0, 0, 0, 0, 1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.