Returning the positions of a list that are non-zero

Andrii V. Mishkovskyi mishok13 at gmail.com
Wed Jul 9 09:20:24 EDT 2008


2008/7/9 Benjamin Goudey <bwgoudey at gmail.com>:
> 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

>>> l = [0, 0, 1, 2, 1, 0, 0]
>>> zip(*[(item, index) for (index, item) in enumerate(l) if item != 0])
[(1, 2, 1), (2, 3, 4)]


> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Wbr, Andrii Mishkovskyi.

He's got a heart of a little child, and he keeps it in a jar on his desk.



More information about the Python-list mailing list