How to Combine Each of the Elements of Two Lists in Python?

How to Combine Each of the Elements of Two Lists in Python?

How about something like this:

>>> import itertools
>>> foo = [[1, 2, 3], [4, 5, 6], [7, 8, 8]]
>>> for p in itertools.permutations(foo, 2):
...     print zip(*p)
... 
[(1, 4), (2, 5), (3, 6)]
[(1, 7), (2, 8), (3, 8)]
[(4, 1), (5, 2), (6, 3)]
[(4, 7), (5, 8), (6, 8)]
[(7, 1), (8, 2), (8, 3)]
[(7, 4), (8, 5), (8, 6)]

Edit:
In case you only want to zip a list with those after it, as people in comments are explaining:

>>> import itertools
>>> for p in itertools.combinations(foo, 2):
...     print zip(*p)
... 
[(1, 4), (2, 5), (3, 6)]
[(1, 7), (2, 8), (3, 8)]
[(4, 7), (5, 8), (6, 8)]

You will only be able to accomplish your intended result if you have an even number of lists. This code will produce the intended result. There may be something more pythonic, however.

foo = [[1,2,3,4,5],[6,7,8,9,0],[2,5,7,9,4],[4,7,8,43,6]]
newlist = []

for i in xrange(len(foo)):
    if i % 2 == 0:
        list1 = foo[i]
        list2 = foo[i + 1]
        for n in xrange(len(list1)):
            newlist.append([list1[n],list2[n]])

print newlist

Result:

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

How to Combine Each of the Elements of Two Lists in Python?

a=[[1,2,3,4,5],[6,7,8,9,0],[2,5,7,9,4],[4,7,8,43,6]]

i=0

for l in a[i:]:
    for inner in a[i+1:]:
        print [list(b) for b in zip(l, inner)]
    i += 1

prints

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

Leave a Reply

Your email address will not be published.