Maf
Maf

Reputation: 735

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)?

Upvotes: 0

Views: 310

Answers (2)

Arnab De
Arnab De

Reputation: 462

(Explicit is better than implicit. Simple is better than complex.) I would use list-comprehension for its flexiblity:

list((x, (x[0][1], x[1][1])) for x in list(combinations(enumerate(my_list), 2)))

This can be further extended using the likes of opertor.itemgetter.

Also, the idea is to run use the iterator only once, so that the method can potentially be applied to other non-deterministic iterators as well, say, an yield from random.choices.

Upvotes: 0

Daniel Hao
Daniel Hao

Reputation: 4980

@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))]

Upvotes: 1

Related Questions