Returning the positions of a list that are non-zero

Paul McGuire ptmcg at austin.rr.com
Wed Jul 9 10:37:54 EDT 2008


On Jul 9, 12:26 am, Benjamin Goudey <bwgou... at gmail.com> wrote:
> I have a very large list of integers representing data needed for a
> histogram that I'm going to plot using pylab. However, most of these
> values (85%-95%) are zero and I would like to remove them to reduce
> the amount of memory I'm using and save time when it comes to plotting
> the data. To do this, I'm trying to find the best way to remove all of
> the zero values and produce a list of indices of where the non-zero
> values used to be.
>
> For example, if my original list is [0,0,1,2,1,0,0] I would like to
> produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices
> of where the non-zero values used to be). Removing non-zero values is
> very easy but determining the indicies is where I'm having difficulty.
>

>>> sparse_data = [0, 0, 1, 2, 1, 0, 0]
>>> values,locns = zip(*[ (x,i) for i,x in enumerate(sparse_data) if x ])
>>> print values
(1, 2, 1)
>>> print locns
(2, 3, 4)
>>>

-- Paul





More information about the Python-list mailing list