Python: combining into lists of lists (?)

First of all, I wanted to say that my title probably incorrectly describes my question. I don’t know the name of the process that I am trying to execute, which makes it very difficult to find a solution in stackoverflow or google. A hint about this could already help me!

I currently have two lists with lists as items. Example:

List1 = [ [a,b], [c,d,e], [f] ] List2 = [ [g,h,i], [j], [k,l] ] 

These lists are basically the vertices of the graph that I am trying to create later in my project, where the edges should be from List1 to List2 line by line.

If we look at the first line of each of the lists, I therefore:

 [a,b] -> [g,h,i] 

However, I want to have bindings / edges of unique elements, so I need:

 [a] -> [g] [a] -> [h] [a] -> [i] [b] -> [g] [b] -> [h] [b] -> [i] 

The result I want to get is another list with these unique settings as elements, i.e.

 List3 = [ [a,g], [a,h], [a,i], [b,g], ...] 

Is there any elegant way to get from List1 and List2 to List 3?

The way I wanted to do this was to sort through line by line, determine the number of elements of each line, and then write sentences and loops to create a new list with all possible combinations. This, however, seems like a very inefficient way to do this.

+5
source share
3 answers

You can zip your two lists, and then use itertools.product to create each of your combinations. You can use itertools.chain.from_iterable to smooth the resulting list.

 >>> import itertools >>> List1 = [ ['a','b'], ['c','d','e'], ['f'] ] >>> List2 = [ ['g','h','i'], ['j'], ['k','l'] ] >>> list(itertools.chain.from_iterable(itertools.product(a,b) for a,b in zip(List1, List2))) [('a', 'g'), ('a', 'h'), ('a', 'i'), ('b', 'g'), ('b', 'h'), ('b', 'i'), ('c', 'j'), ('d', 'j'), ('e', 'j'), ('f', 'k'), ('f', 'l')] 
+13
source

If you don't want to use itertools, you can also use the concept list in conjunction with zip to make it pretty elegant:

 lst1 = [['a','b'], ['c','d','e'], ['f']] lst2 = [['g','h','i'], ['j'], ['k','l']] edges = [[x, y] for il1, il2 in zip(lst1, lst2) for x in il1 for y in il2] 
+2
source
 import itertools k = [] for a,b in zip(List1,List2): for j in itertools.product(a,b): k.append(j) print k 
0
source

All Articles