HI, I'm trying to use for loop to find the difference between every two object by minus each other.
So, how can I find the next value in a for loop?
for entry in entries:
first = entry # Present value
last = ?????? # The last value how to say?
diff = last = first
解决方案
It should be noted that none of these solutions work for generators. For that see Glenn Maynards superior solution.
use zip for small lists:
for current, last in zip(entries[1:], entries):
diff = current - last
This makes a copy of the list (and a list of tuples from both copies of the list) so it's good to use itertools for handling larger lists
import itertools as it
items = it.izip(it.islice(entries, 1, None), entries)
for current, last in items:
diff = current - last
This will avoid both making a copy of the list and making a list of tuples.
Another way to do it without making a copy is
entry_iter = iter(entries)
entry_iter.next() # Throw away the first version
for i, entry in enumerate(entry_iter):
diff = entry - entries[i]
And yet another way is:
for i in xrange(len(entries) - 1):
diff = entries[i+1] - entries[i]
This creates an iterator that indexes entries and advances it by one. It then uses enumerate to get an indice with the item. The indice starts at 0 and so points to the previous element because we the loop one item in.
Also, as Tyler pointed out in the comment, a loop might be overkill for such a simple problem if you just want to iterate over the differences.
diffs = (current - last for current, last in
it.izip(it.islice(entries, 1, None), entries))