python - How to refer to next element in a loop? -


i've been looking around can't find to. i'm sure i've seen done before can't seem find it. here's example:

in case take difference of each element in array,

#generate sample list b = [a**2 in range(10)] #take difference of each element c = [(b+1)-b b in b] 

the (b+1) denote next element in array don't know how , doesn't work, giving result:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 

the result is:

 [1, 3, 5, 7, 9, 11, 13, 15, 17] 

i understand result shorter original array reason replace ugly expressions such as:

 c = [b[i+1]-b[i] in range(len(b)-1)] 

in case isn't bad @ all, there cases need iterate through multiple variables long expressions , gets annoying keep having write index in each time. right i'm hoping there easy pythonic way don't know about...

edit: example of mean having multiple variables be:

 x = [a in range(10)]  y = [a**2 in range(10)]  z = [a**3 in range(10)]   x,y,z in zip(x,y,z):      x + (x+1) + (y-(y+1))/(z-(z+1)) 

where (x+1),(y+1),(z+1) denote next element rather than:

 in range(len(x)):      x[i] + x[i+1] + (y[i]-y[i+1])/(z[i]-z[i+1]) 

i using python 2.7.5 btw

re: edit

zip still right solution. need zip 2 iterators on lists, second of should advanced 1 tick.

from itertools import izip,tee  cur,nxt = tee(izip(x,y,z))  next(nxt,none) #advance nxt iterator  (x1,y1,z1),(x2,y2,z2) in izip(cur,nxt):     print x1 + x2 + (y1-y2)/(z1-z2) 

if don't inline next call, can use islice @felixkling mentioned: izip(cur,islice(nxt, 1, none)).


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -