Python et les boucles imbriquées via itertools.product

Publié le 28 mars 2013 par Mikebrant

Vous avez un code avec plein de for imbriqués ?

Et bien itertools.product est fait pour vous.

Code moche:

a = ['un']
b = a + ['deux']
c = b + ['trois']
d = c + ['quatre']

for i in a:
    for j in b:
        for k in c:
            for l in d:
                print i,j,k,l

Devient :

a = ['un']
b = a + ['deux']
c = b + ['trois']
d = c + ['quatre']

for i, j, k, l in itertools.product(a,b,c,d):
    print i,j,k,l

Bien plus lisible.