pythonlistcombinations

Create a list of pairs, by position, from multiple other lists


I need to make a list of pairs from several other lists. The pairs will consist of a value from the same position in each list. There could be a varying number of lists, but each list will have the same number of values. It's not quite combinations/permuations I think because some values need to be repeated.

Easier to explain with an example:

list_a = [1, 2, 3, 4, 5]
list_b = [6, 7, 8, 9, 10]
list_c = [11, 12, 13, 14, 15]
list_d = [16, 17, 18, 19, 20]

Output required = [(1,6),(6,11),(11,16),(2,7),(7,12),(12,17)....etc]

The output doesn't necessarily have to be a list of tuples but I figured something like that would be most reasonable. It could be separated further with each 'column' of pairs being their own list, but that's not important.

I was going to brute force it with loops but I'm sure there's a better way. I feel like it's down the path of zips and itertools but I can't get it. This post about equal sized chunks was almost it, but you can see from the example above that I need to re-use the preceeding value in the next pair. How do I split a list into equally-sized chunks?


Solution

  • This can be done using two nested calls to zip:

    list_a = [1, 2, 3, 4, 5]
    list_b = [6, 7, 8, 9, 10]
    list_c = [11, 12, 13, 14, 15]
    list_d = [16, 17, 18, 19, 20]
    
    lists = [list_a, list_b, list_c, list_d]
    
    output = [y for x in zip(*lists) for y in zip(x, x[1:])]
    
    print(output)
    

    Output:

    [(1, 6), (6, 11), (11, 16), (2, 7), (7, 12), (12, 17), (3, 8), (8, 13), (13, 18), (4, 9), (9, 14), (14, 19), (5, 10), (10, 15), (15, 20)]
    

    The first call to zip produces tuples of the first element, second element, etc of each list.

    The second call to zip creates pairs of (first, second), (second, third), (third, fourth), etc.