[CentralOH] Handy function to decimate a list of numbers (get every Nth item)

David Car david.car7 at gmail.com
Thu Mar 19 01:22:59 CET 2009


Yeah, Marks is the fast way to do it.

Regards,

David


On Wed, Mar 18, 2009 at 5:02 PM, Mark Erbaugh <mark at microenh.com> wrote:

> On Wed, 2009-03-18 at 16:48 -0400, Bryan Harris wrote:
> > Hey all, I came up with this little snippet to get every Nth line in a
> list.
> > Google didn't turn anything up in the first few pages.  Does anybody know
> a
> > better way?  This seems like the kind of thing python would be able to do
> > automatically using the % (modulo) symbol or something.
> >
> > Code:
> > def decimate(array,points):
> >     if type(points) != type(1):  #line 1.5 doesn't mean anything!
> >         raise Error, "number of points should be an integer"
> >
> >     if len(array)/2<=points:  #Not worth doing for an array this small
> >         return array
> >
> >     new_array=[]
> >     #get the line numbers rather than stepping through the entire list
> >     interval=int(len(array)/points)
> >     line_numbers = range(0,len(array),interval)
> >
> >     for each in line_numbers:
> >         new_array=new_array + [array[each]]
> >     return(new_array)
> >
> >
>
>
> How about array[::points]?
>
> demo:
>
> array = ['Line %d] % i for i in range(100)]
>
> array[::10]
>
> ['Line 0', 'Line 10', ... 'Line 90']
>
> Mark
>
>
>
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> http://mail.python.org/mailman/listinfo/centraloh
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20090318/fa83fbde/attachment.htm>


More information about the CentralOH mailing list