FairyDuster FairyDuster - 1 month ago 10
Python Question

How to make a nested for loop using a generator in python?

I'm trying to convert this nested for loop:

for k,v in all_R.iteritems():
for pairs in v:
print pairs[1]


to a one liner, something like this:

print ([pairs[1] for pairs in v for k,v in all_R.iteritems()])


But I'm getting this error:

UnboundLocalError: local variable 'v' referenced before assignment


all_R is a defaultdict where every value has keys that are pairs, and I'm interested in just one value from that pair:

{'1-0002': [('A-75G', 'dnaN'), ('I245T', 'recF'),... ], '1-0004': [('A-75G', 'dnaN'), ('L161', 'dnaN'),...]}

Answer

List comprehensions are written in the same order as for loops, so you are actually looking for (Note the order is reversed) print ([pairs[1] for k,v in all_R.iteritems() for pairs in v ])

If you are looking to use generators as your title suggests, you can use parenthesis instead of brackets (pairs[1] for k,v in all_R.iteritems() for pairs in v)

That will create a generator with your desired properties.

Comments