Reputation: 621
I have this piece of code, it's not working and I have no idea why.
My data structure:
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
Upvotes: 0
Views: 120
Reputation: 37003
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.
Upvotes: 2