0

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

7
  • 2
    Just zip the two iterators, rather than consuming them into lists. Commented Dec 29, 2020 at 15:11
  • Could you please help me how to do that? Commented Dec 29, 2020 at 15:12
  • 1
    See docs.python.org/3/library/functions.html#zip Commented Dec 29, 2020 at 15:13
  • Thank you. I'm reading to get the solution ASAP. Commented Dec 29, 2020 at 15:17
  • 1
    I don't think the output from your second example is correct, if you're taking combinations of the tuples from enumerate that would be the values and their indices, the first item emitted would be ((0, 7), (1, 5)). What you show would be the output from combinations of the indices alone, e.g. from range(len(my_list)). Commented Dec 29, 2020 at 15:35

2 Answers 2

1

@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))]
Sign up to request clarification or add additional context in comments.

1 Comment

We were writing at the same time. It seems to be the best solution. I'm going to to choose your answer. Thanks for answering!
0

(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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.