list - Reduce indentation when using Python nested loops -


is there way reduce indentation when using nested loops, per below?

for source_i in sources:     source_j in sources:         ni in source_i.nodes:             nj in source_j.nodes:                 if ni != nj:                     do_thing(ni, nj) 

for source_i in sources:     source_j in sources:         pass 

this same thing iterating through pairs in cartesian product of sources , itself. can written in 1 line importing itertools:

import itertools (i,j) in itertools.product(sources, repeat=2):     pass 

same pattern here:

for ni in i.nodes:     nj in j.nodes:         pass 

this can rewritten as:

for (ni, nj) in itertools.product(i.nodes, j.nodes):     pass 

so can nest them:

import itertools (i,j) in itertools.product(sources, repeat=2):     (ni, nj) in itertools.product(i.nodes, j.nodes):         if ni != nj:             do_thing(ni, nj) 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -