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?
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?
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
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]]