Read other items in a python list while iterating through it [duplicate]
Possible Duplicate:
Python: Looping through all开发者_运维问答 but the last item of a list
Is there a better way of iterating through a list when you also need the next item (or any other arbitrary item) in the list? I use this, but maybe someone can do better...
values = [1, 3, 6, 7 ,9]
diffs = []
for i in range(len(values)):
try: diffs.append(values[i+1] - values[i])
except: pass
print diffs
gives:
[2, 3, 1, 2]
>>> values = range(10)
>>> values
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> zip(values[0:],values[1:])
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
what about with the aid of pairwise recipe from itertools document
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
def main():
values = [1, 3, 6, 7 ,9]
diffs = [post - prior for prior, post in pairwise(values)]
print diffs
if __name__ == "__main__":
main()
output
[2, 3, 1, 2]
You could use
for pos, item in enumerate(values):
try:
diffs.append(values[pos+1] - item)
except IndexError:
pass
although in your case (since you're just looking for the next value), you could also simply use
for item,nextitem in zip(values, values[1:]):
diffs.append(nextitem-item)
which can also be expressed as a list comprehension:
diffs = [nextitem-item for item,nextitem in zip(values, values[1:])]
for i, j in zip(values, values[1:]):
j - i
diff = [values[i+1] - values[i] for i in range(len(values)-1)]
[y - x for x,y in zip(L,L[1:])]
精彩评论