The phrase ‘every Nth item‘ may be off here, but it is close enough what I want to do (reduce a data set for charting purposes).
# data = sequence of data items
# nth = you want every nth element in the array
[data[index] for index in xrange(0, len(data), nth)]
for example:
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print [data[index] for index in xrange(0, len(data), 2)] # [1, 3, 5, 7, 9] print [data[index] for index in xrange(0, len(data), 3)] # [1, 4, 7, 10] print [data[index] for index in xrange(0, len(data), 4)] # [1, 5, 9] print [data[index] for index in xrange(0, len(data), 5)] # [1, 6]
You could also use data[::n] to get every nth item. It is a lot shorter and clearer probably.
Or, data[::2], data[::3], data[::4], etc.
I think you’ll find data[0::2] faster, in more ways than one.
Very nice. I will use this in the future. Thanks.
>>> data= range(1, 11)
## A list from a list:
## data[::step]
>>> data[::2]
[1, 3, 5, 7, 9]
>>> data[::3]
[1, 4, 7, 10]
## An iterable from an iterable
## itertools.islice(data, 0, None, step)
for item in itertools.islice(data, 0, None, 2):
…
what’s wrong with `data[::n]`?
What about
>>> print data[::n]
where n is the desired step
More generally:
data[begin:excluded end:step]
See http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange
data[::2] ?
What about using itertools.islice?
Or you could use:
data[::2]
etc
import itertools
print list(itertools.islice(data, 0, None, 2)
print list(itertools.islice(data, 0, None, 3)
etc
Thanks everyone, I didn’t know about the other options – especially data[::2]. Just goes to show you that there is always something more to learn.