Baff
Baff

Reputation: 47

Iterate through arraylist calculating the difference of consecutive values in python

i'm trying to iterate over an arraylist saving in every loop the highest/lowest difference of the consecutive values.

e1=([ 0 , 0,  0,  0, 15, 28, 28, 28, 27, 27, 35, 44, 43, 43, 42, 39])
Hodiffmax = 0
Hodiffmin = 0
for k in e1:
  diff1= e1[k+1] - e1[k]
  if diff1 > Hodiffmax:
      Hodiffmax=diff1
  if diff1 < Hodiffmin:
      Hodiffmin=diff1

The problem is i get an "index out of bound" error. How can i iterate through an arraylist with [k+1]? I tried a bunch of things now but i dont get smarter. I appreciate any help!

EDIT (that works neither):

for k in e1:
    for w in k:
      diff1= e1[w+1] - e1[w]
      if diff1 > Hodiffmax:
          Hodiffmax=diff1
      if diff1 < Hodiffmin:
          Hodiffmin=diff1

Error: for w in k - TypeError: 'numpy.int32' object is not iterable

Upvotes: 1

Views: 1334

Answers (3)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Use the grouper recipe:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

from itertools import izip_longest # required by grouper
i = [0, 0, 0, 0, 15, 28, 28, 28, 27, 27, 35, 44, 43, 43, 42, 39]
lowest = None
highest = None
for z,q in grouper(i, 2):
    v = z-q
    if v < lowest:
        lowest = v
    if v > highest:
        highest = v
print(lowest)
print(highest)

Upvotes: 2

GabrielOshiro
GabrielOshiro

Reputation: 8322

The problem here is that you are iterating over the elements of the list. By doing

for k in e1:

k will get the values of the elements on e1. k=0, k=0, k=0, k=0, k=15, k=28 and so on. What you want instead is to iterate over the range of the list.

for k in range(len(e1)):

k will get the values of indexes on e1. k=0, k=1, k=2, k=3, k=4, k=5 and so on. I think you were looking for something like this:

e1 = [0, 0, 0, 0, 15, 28, 28, 28, 27, 27, 35, 44, 43, 43, 42, 39]

for k in range(len(e1)):
  print k
  if k > 0:
    diff1 = e1[k] - e1[k-1]
    if diff1 > Hodiffmax:
      Hodiffmax=diff1
    if diff1 < Hodiffmin:
      Hodiffmin=diff1

print 'Hodiffmax ' + str(Hodiffmax)
print 'Hodiffmin ' + str(Hodiffmin)

Upvotes: 0

JuniorCompressor
JuniorCompressor

Reputation: 20015

With [y - x for x, y in zip(e1, e1[1:])] you can get consecutive differences without worrying for the indexes:

>>> e1 = [ 0 , 0,  0,  0, 15, 28, 28, 28, 27, 27, 35, 44, 43, 43, 42, 39]
>>> l = [y - x  for x, y in zip(e1, e1[1:])]
>>> Hodiffmax, Hodiffmin = max(l), min(l)
>>> Hodiffmax, Hodiffmin
15, -3

Upvotes: 3

Related Questions