Skip to content Skip to sidebar Skip to footer

How Flatten A List Of Lists One Step

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

Solution 1:

itertools.product(*A)

For more details check the python tutorial

Solution 2:

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

itertools.product(*A)

Solution 3:

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.

Solution 4:

Late to the party but ...

I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):

def flatten(lst):
    if lst:
        car,*cdr=lst
        if isinstance(car,(list)):
            if cdr: return flatten(car) + flatten(cdr)
            return flatten(car)
        if cdr: return [car] + flatten(cdr)
        return [car]

Seems to work. Test:

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

flatten(A)

Result:

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

Note: the line car,*cdr=lst only works in Python 3.0

Solution 5:

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):
    iflen(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

Post a Comment for "How Flatten A List Of Lists One Step"