[CentralOH] Handy function to decimate a list of numbers (get every Nth item)
Mark Erbaugh
mark at microenh.com
Wed Mar 18 22:02:39 CET 2009
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
More information about the CentralOH
mailing list