Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a huge group of lists within lists that I want to combine: It looks sort of like this:

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

up to about 20 of these lists in a list. I now want to combine the first list and second list to look like this:

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

And then I want to do it again with the 1st and 3rd, all the way until the end. And then do it again starting with the second list to 3rd,4th...last line (but not the first one because that was already done with 1st to 2nd list). How can I write code that will do this?

Here is what I have so far:

xcols = the column with all the lists like I showed above

def MakeLists(xcols):
    multilist = []
    for i in xcols:
        for j in xcols[index(i):]:
            currentlist = map(list.__add__, i, j)
            multilist.append(currentlist)

Gives me an error when I run it though, probably at the map part because I don't know how to first convert each element into a list and then map them. Any help would be great. Thanks!

like image 811
LiamNeesonFan Avatar asked Dec 04 '11 00:12

LiamNeesonFan


1 Answers

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)]
like image 67
stranac Avatar answered Sep 20 '22 20:09

stranac