简体   繁体   中英

python: how can I achieve a cartesian product of all the lists in a list?

In particular I am looking if there is some cartesian_product() method built into python or a way to do this with itertools avoid having to write a nested multidimension loop.

for example I have the following

input = [
   [1], 
   [[2]], 
   [3], 
   [[a,b,c] , [[z,x,y]] , [d,f,g]], 
   4
]

expecting:

output = [
    [1,2,3,a,b,c,4]
    [1,2,3,z,x,y,4]
    [1,2,3,d,f,g,4]
]

The one particular challenge is that as in the above input list, an item can have any layer of lists, but it should be able to ignore all of those and still produce a flattened result.

input = [
    [1], 
    [[2]], 
    [3], 
    [['a','b','c'] , [['z','x','y']], ['d','f','g']], 
    4
]

input = map(lambda(x): x if isinstance(x, list) else [x], input)

import itertools
for element in itertools.product(*input):
    print element

To add on top of @rorra's answer, in order to print the results "flattened", add the following function:

def flat(l):
    def _flat(l, r):    
        if type(l) is not list:
            r.append(l)
        else:
            for i in l:
                r = r + flat(i)
        return r
    return _flat(l, [])

and then (rorra's code with a slight modification):

_input = [
    [1], 
    [[2]], 
    [3], 
    [['a','b','c'] , [['z','x','y']], ['d','f','g']], 
    4
]

_input = map(lambda(x): x if isinstance(x, list) else [x], _input)

import itertools
for element in itertools.product(*_input):
    print flat(list(element))  # this line was modified

OUTPUT

[1, 2, 3, 'a', 'b', 'c', 4]
[1, 2, 3, 'z', 'x', 'y', 4]
[1, 2, 3, 'd', 'f', 'g', 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM