ups ups - 1 year ago 64
Python Question

how to convert nested loops to nested comprehensive list in python?

I have problem convert 3 level loop to comprehensive list

for a in X:
for b in a:
for c in b:

I want it in list just as quick-tool to verify code.
I understand pros and cons and know itertools.chain function.

solution for 2 level is:

[do(b) for a in X for b in a]

solution for 3 level is:

[do(c) for b in itertools.chain.from_iterable(X) for c in b]

how it will looks without using chain ? just list expression.

Answer Source
[c for a in X for b in a for c in b]

is the flattened version of X. The for clauses appear in the same order that they do in the nested loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download