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

HI, I'm trying to use for a loop to find the difference between every two objects 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
+3
source share
4 answers

It should be noted that none of these solutions works for generators. For this, see Glenn Maynards 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 is useful to use itertools to process large 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 copying a list copy and compiling a list of tuples.

Another way to do this 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]

:

for i in xrange(len(entries) - 1):
    diff = entries[i+1] - entries[i]

, entries . enumerate . 0 , .

, , , .

diffs = (current - last for current, last in 
         it.izip(it.islice(entries, 1, None), entries))
+11

zip , :

def pairs(it):
    it = iter(it)
    prev = next(it)
    for v in it:
        yield prev, v
        prev = v

a = [1,2,3,4,5]
for prev, cur in pairs(a):
    print cur - prev

import itertools as it
for prev, cur in pairs(it.cycle([1,2,3,4])):
    print cur - prev

, , , :

for prev, cur in pairs(open("/usr/share/dict/words").xreadlines()):
    print cur, prev,

: , , ( " " ), , , - .

+5

very simple using enumeration, not fancy things

>>> entries=[10,20,30,40]
>>> for n,i in enumerate(entries):
...     try:
...        print entries[n+1] - i
...     except IndexError:
...        print entries[-1]
...
10
10
10
40
+1
source

I don’t know exactly what you are looking for, but maybe this can help:

first = entries[0]
for entry in entries[1:]:
    last = entry       
    diff = last - first 
    first = entry
+1
source

Source: https://habr.com/ru/post/1769446/


All Articles