Skip to content
Advertisement

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

I’m trying to convert this nested for loop:

JavaScript

to a one liner, something like this:

JavaScript

But I’m getting this error:

JavaScript

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

JavaScript

Advertisement

Answer

List comprehensions are written in the same order as for loops, so you are actually looking for (Note the order is reversed)

JavaScript

Here’s a break down that shows the structure a bit more clearly:

JavaScript

If you are looking to use generators as your title suggests, you can use parenthesis instead of brackets.

JavaScript

That will create a generator with your desired properties.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement