With list comprehension, you can easily loop through all combinations of 2 or 3 lists. But what about more, like 4,6, 20? This recipe show a way to do this, without use of recursion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | a = [[1,2],[3,4,5],[6],[7,8,9,10]]
r=[[]]
for x in a:
t = []
for y in x:
for i in r:
t.append(i+[y])
r = t
print r
-------------------------------
[[1, 3, 6, 7], [2, 3, 6, 7], [1, 4, 6, 7], [2, 4, 6, 7], [1, 5, 6, 7], [2, 5, 6, 7], [1, 3
, 6, 8], [2, 3, 6, 8], [1, 4, 6, 8], [2, 4, 6, 8], [1, 5, 6, 8], [2, 5, 6, 8], [1, 3, 6, 9
], [2, 3, 6, 9], [1, 4, 6, 9], [2, 4, 6, 9], [1, 5, 6, 9], [2, 5, 6, 9], [1, 3, 6, 10], [2
, 3, 6, 10], [1, 4, 6, 10], [2, 4, 6, 10], [1, 5, 6, 10], [2, 5, 6, 10]]
|
At each outermost iteration, the number of result list r multiply by the number of items of current item(list). At each inner iteration, the list item i (itself is a list) is replace by a new list.
Tags: shortcuts
Improve by using list comprehension. The lines within the outer loop could be replaced with a list comprehenstion like:
Thank you very much, I am looking for this function and helped in my work
Good work. But I'm going to play devils advocate and ask why you didn't just use itertools.product? http://docs.python.org/library/itertools.html?highlight=itertools#itertools.product