tags:

views:

321

answers:

5

I have a list of lists of tuples

A= [ [(1,2,3),(4,5,6)], [(7,8,9),(8,7,6),(5,4,3)],[(2,1,0),(1,3,5)] ]

The outer list can have any number of inner lists, the inner lists can have any number of tuples, a tuple always has 3 integers.

I want to generate all combination of tuples, one from each list:

[(1,2,3),(7,8,9),(2,1,0)]
[(1,2,3),(7,8,9),(1,3,5)]
[(1,2,3),(8,7,6),(2,1,0)]
...
[(4,5,6),(5,4,3),(1,3,5)]

A simple way to do it is to use a function similar to itertools.poduct() but it must be called like this

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

i.e the outer list is removed. And I don't know how to do that. Is there a better way to generate all combinations of tuples?

+5  A: 
itertools.product(*A)

For more details check the python tutorial

Nadia Alramli
+1  A: 

This works for your example, if there is only one level of nested lists (no lists of lists of lists):

itertools.product(*A)
Triptych
+1  A: 

you can probably call itertools.product like so:

itertools.product(*A) # where A is your list of lists of tuples

This way it expands your list's elements into arguments for the function you are calling. This may not work though depending on how product's signature works but it's worth a try.

Kevlar
+1  A: 

This is not exactly one step, but this would do what you want if for some reason you don't want to use the itertools solution:

def crossprod(listoflists):
    if len(listoflists) == 1:
        return listoflists
    else:
        result = []
        remaining_product = prod(listoflists[1:])
        for outertupe in listoflists[0]:
            for innercombo in remaining_product[0]:
                newcombo = [outertupe]
                newcombo.append(innercombo)
                result.append(newcombo)
        return result
dsimard
A: 
def flatten(A)
    answer = []
    for i in A:
        if type(i) == list:
         ans.extend(i)
    else:
     ans.append(i)
    return ans
inspectorG4dget
you need to fix your indentation.
SilentGhost
Terribly sorry for indentation errors. Turns out that copying code from my local IDE does not preserve proper indentation when I paste here
inspectorG4dget