Search code examples
arrayspython-3.xlistcombinationspython-itertools

Python itertools.combinations: how to obtain the indices of the combined numbers within the combinations at the same time


According to the question presented here: Python itertools.combinations: how to obtain the indices of the combined numbers, given the following code:

import itertools
my_list = [7, 5, 5, 4]

pairs = list(itertools.combinations(my_list , 2))
#pairs = [(7, 5), (7, 5), (7, 4), (5, 5), (5, 4), (5, 4)]

indexes = list(itertools.combinations(enumerate(my_list ), 2)
#indexes = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

Is there any way to obtain pairs and indexes in a single line so I can have a lower complexity in my code (e.g. using enumerate or something likewise)?


Solution

  • @Maf - try this, this is as @jonsharpe suggested earlier, use zip:

    from pprint import pprint
    from itertools import combinations
    
     my_list = [7, 5, 5, 4]
    >>> pprint(list(zip(combinations(enumerate(my_list),2), combinations(my_list,2))))
    [(((0, 7), (1, 5)), (7, 5)),
     (((0, 7), (2, 5)), (7, 5)),
     (((0, 7), (3, 4)), (7, 4)),
     (((1, 5), (2, 5)), (5, 5)),
     (((1, 5), (3, 4)), (5, 4)),
     (((2, 5), (3, 4)), (5, 4))]