Returning the positions of a list that are non-zero

Rajanikanth Jammalamadaka rajanikanth at gmail.com
Wed Jul 9 01:48:26 EDT 2008


Try this:

>>> li=[0,0,1,2,1,0,0]
>>> li
[0, 0, 1, 2, 1, 0, 0]
>>> [i for i in range(len(li)) if li[i] != 0]
[2, 3, 4]

Cheers,

Raj

On Tue, Jul 8, 2008 at 10:26 PM, Benjamin Goudey <bwgoudey 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.
>
> Thanks in advance for any help
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
"For him who has conquered the mind, the mind is the best of friends;
but for one who has failed to do so, his very mind will be the
greatest enemy."

Rajanikanth



More information about the Python-list mailing list