简体   繁体   中英

Iterator inside for-loop: why is this not working?

I have this piece of code, it's not working and I have no idea why.

My data structure:

  • "genes" is a dictionary with as key it's ID, as value multiple instances of the object Gene.
  • the Gene object contains a similar dictionary with instances of the object "Transcript".

Finally, "parent" is an ID of a Transcript (string). I need to get the Transcript instance (ptrans) which has the same ID as the string "parent". It is inside one of the Gene instances.

When I am running the code at the bottom, I don't get a real exception, but a "StopIteration", which I thought I catch, whereafter it should continue with the next Gene object, right?:

Traceback (most recent call last): File "<stdin>", line 1, in <module> ... ptrans = next(t for t in g.transcripts.values() if t.ID == parent) StopIteration

I could do it with a nested for-loop, but I though this might work aswell. I just can't get my head around the fact that this does not work. Can anyone explain why, or how it might work?

    # iterate over Gene-dict
    for g in genes.values(): 
        #Iterate over Transcripts in 1 Gene
        try:
            ptrans = next(t for t in g.transcripts.values() if t.ID == parent)
        #If no match, continue
        except StopIteration:
            continue
        if ptrans:
                break

Your code

ptrans = next(t for t in g.transcripts.values() if t.ID == parent)

almost certainly isn't doing what you think. I suspect that there are no items in g.transcript.values() that have the parent as their ID, since calling next() on an empty generator would indeed raise a StopIteration error.

The next() function, however, will in any case only be called once, meaning that even if there are valid values only the first one would ever be returned. Nested loops are a much simpler way to achieve what you are trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM