Search code examples
pythonenumerate

Enumerate, print previous


I have a dictionary that looks something like this:

{'NM_014043': [(0, 34), (13176, 13268), (18191, 18386), (22352, 22455), (25881, 25988), (26189, 26300)],

and a file that contains a positions, as such:

isoform    pos_rein
NM_014043    13177

I've written my script as shown below:

import csv
with open('splicing_reinitialized.txt') as f:
    reader = csv.DictReader(f,delimiter="\t")
    for row in reader:
        pos = row['pos_rein']
        name = row['isoform']
        ppos1 = int(pos)
        if name in exons:
            y = exons[name]
            for i, (low,high) in enumerate(exons[name]):
                if low -3 <= ppos1 <= high + 6:
                    exonnumber = i+1
                    values = (low,high)
                    print values

My problems is that my values variable prints the current set of numbers it's associated with (in this case (13176, 13268)), but what I want to do is to print the previous numbers (0, 34) instead of the numbers the position is associated with. Is there anyway to do such a thing easily?


Solution

  • Just store the current numbers in the loop; the next iteration they'll be the previous values until you assign again:

    previous = None
    for i, (low,high) in enumerate(exons[name]):
        if low -3 <= ppos1 <= high + 6:
            exonnumber = i+1
            print previous
            previous = low, high