0

I often work with numpy arrays representing critical times in a time series. I then want to iterate over the ranges and run operations on them. Eg:

rngs = [0, 25, 36, 45, ...]
output = []
for left, right in zip(rngs[:-1], rngs[1:]):
      throughput = do_stuff(array[left:right])...
      output.append(throughput)

Is there a less awkward way to do this?

AGML
  • 890
  • 6
  • 18
  • Assuming the `rngs` are irregular and `dostuff` can only work on one slice at a time, that looks good. But also look at `ufunc.reduceat` – hpaulj Mar 10 '16 at 13:25
  • Possible duplicate of [Iterate a list as pair (current, next) in Python](http://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python) – Reti43 Mar 10 '16 at 13:25
  • Though I think he wants something special for `numpy`; not just a list. – hpaulj Mar 10 '16 at 13:37

1 Answers1

0

You might use enumerate generator

rngs = [0, 25, 36, 45, ...]
output = []
for index, _ in enumerate(rngs[:-1]):
      throughput = do_stuff(array[index:index+1])...
      output.append(throughput)

in one line with comprehension list:

rngs = [0, 25, 36, 45, ...]
output = [do_stuff(array[index:index+1]) for index, _ in enumerate(rngs[:-1])]
mvelay
  • 1,520
  • 1
  • 10
  • 23
  • I see no difference between this and `for index in range(len(rngs)-1):`, or `xrange()` for Python 2. Additionally, there is no tuple unwrapping like in `index, _` and you don't have to construct `rngs[:-1]`. – Reti43 Mar 10 '16 at 13:24