开发者

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


itertools.product(*A)

For more details check the python tutorial


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

itertools.product(*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.


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


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


def flatten(A)
    answer = []
    for i in A:
        if type(i) == list:
            ans.extend(i)
        else:
            ans.append(i)
    return ans


This may also be achieved using list comprehension.

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

In [63]: improved_list = [num for elem in A for num in elem]

In [64]: improved_list
Out[64]: [(1, 2, 3), (4, 5, 6), (7, 8, 9), (8, 7, 6), (5, 4, 3), (2, 1, 0), (1, 3, 5)]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜