Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

python for loop, how to find next value(object)?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...