0

for example

a = [1, 2, 3]
b = [4, 5, 6, 7]
c = [8, 9]

for i in a:
    for l in b:
        for h in c:
            print [i,l,h]

but what if there is d, e ,f...

I want define a function can print them all but not use nested for.

how to do it?

zztczcx
  • 430
  • 1
  • 5
  • 19
  • 1
    I was going to link [this](http://stackoverflow.com/questions/11174745/avoiding-nested-for-loops) as the dup, but they're both good. :-) – DSM Oct 14 '14 at 17:44

2 Answers2

1

You can use itertools.product

>>> import itertools
>>> list(itertools.product(a,b,c))
[(1, 4, 8), (1, 4, 9), (1, 5, 8), (1, 5, 9), (1, 6, 8), (1, 6, 9), (1, 7, 8), (1, 7, 9),
 (2, 4, 8), (2, 4, 9), (2, 5, 8), (2, 5, 9), (2, 6, 8), (2, 6, 9), (2, 7, 8), (2, 7, 9),
 (3, 4, 8), (3, 4, 9), (3, 5, 8), (3, 5, 9), (3, 6, 8), (3, 6, 9), (3, 7, 8), (3, 7, 9)]

So to iterate and do stuff with the numbers, you could say

for i, j, k in itertools.product(a,b,c):
    # do stuff with i,j,k
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

Your nested for loops create the products of lists so you can use itertools.product instead !

>>> import itertools

>>> list(itertools.product([1, 2, 3],[4, 5, 6, 7],[8, 9]))
[(1, 4, 8), (1, 4, 9), (1, 5, 8), (1, 5, 9), (1, 6, 8), (1, 6, 9), (1, 7, 8), (1, 7, 9), (2, 4, 8), (2, 4, 9), (2, 5, 8), (2, 5, 9), (2, 6, 8), (2, 6, 9), (2, 7, 8), (2, 7, 9), (3, 4, 8), (3, 4, 9), (3, 5, 8), (3, 5, 9), (3, 6, 8), (3, 6, 9), (3, 7, 8), (3, 7, 9)]

and if you want the result as list , use map :

>>> map(list,itertools.product([1, 2, 3],[4, 5, 6, 7],[8, 9]))
[[1, 4, 8], [1, 4, 9], [1, 5, 8], [1, 5, 9], [1, 6, 8], [1, 6, 9], [1, 7, 8], [1, 7, 9], [2, 4, 8], [2, 4, 9], [2, 5, 8], [2, 5, 9], [2, 6, 8], [2, 6, 9], [2, 7, 8], [2, 7, 9], [3, 4, 8], [3, 4, 9], [3, 5, 8], [3, 5, 9], [3, 6, 8], [3, 6, 9], [3, 7, 8], [3, 7, 9]]
Mazdak
  • 105,000
  • 18
  • 159
  • 188