How to enumerate combinations by tuple indices?

According to the Python docs, combinations follows this sort of pattern:

# combinations('ABCD', 2) --> AB AC AD BC BD CD

I’ll be specific about my use case, hopefully without losing generality. I’d like to compute a pairwise metric for a sequence of objects like this:

from itertools import combinations
metrics = [metric(a,b) for (a, b) in combinations(objects, 2)]

Then I want to grab pairs of my objects based on some metric threshold. To do so I’d need to invert this correspondence combinations('ABCD', 2) --> AB AC AD BC BD CD. Ideally, I’d like to avoid writing any logic that does this, and just get it from the source of truth: the combinations function.

I’d like to enumerate like this:

metrics = {(i, j): metric(a,b) for (i, j), (a, b) in enumerate(combinations(objects, 2))}

But of course this doesn’t yield a tuple index, just an integer index.

How do I get what I’m looking for?

Answer

You can enumerate the objects and make combinations of those.

metrics = {(i, j): metric(a,b) for (i, a), (j, b) in combinations(enumerate(objects), 2)}