[CentralOH] Handy function to decimate a list of numbers (get every Nth item)
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.
> 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
> #get the line numbers rather than stepping through the entire list
> line_numbers = range(0,len(array),interval)
> for each in line_numbers:
> new_array=new_array + [array[each]]
How about array[::points]?
array = ['Line %d] % i for i in range(100)]
['Line 0', 'Line 10', ... 'Line 90']
More information about the CentralOH