-1

Here's a snippet with a regular itertools.product usage:

from itertools import product

arr = [1,2,3]
pairs = list(product(arr, arr))

# pairs = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

Now I would like to have these points yielded in an order which can be achieved by sorting the resulting tuples in the following way:

sorted(pairs, key=lambda y:max(y))
# [(1, 1), (1, 2), (2, 1), (2, 2), (1, 3), (2, 3), (3, 1), (3, 2), (3, 3)]

Is there a way for me to input those numbers to itertools.product so it yields the tuples in this order, or do I need to sort the pairs after iterating over the results of itertools.product?

mrapacz
  • 889
  • 8
  • 22
  • the latter, you've got it right. – Paritosh Singh May 24 '19 at 10:09
  • 1
    Please, clarify _I want the smallest numbers to appear first._ – sentence May 24 '19 at 10:09
  • Yes, you need to sort the pairs, from the docs: https://docs.python.org/3/library/itertools.html#itertools.product `product(A, B) returns the same as ((x,y) for x in A for y in B).` – Devesh Kumar Singh May 24 '19 at 10:10
  • @sentence As specified in the question "I want the smallest numbers to appear first" is visualized just below using the `sorted` expression i.e. I want to have the tuples sorted by max() of their elements – mrapacz May 24 '19 at 10:12
  • 2
    `sorted` is [guaranteed to be **stable**](https://stackoverflow.com/questions/1915376/is-pythons-sorted-function-guaranteed-to-be-stable), so your own attempt is correct assuming that the *input array itself is sorted*. – meowgoesthedog May 24 '19 at 10:13
  • 1
    You could avoid the sort by generating them directly in the desired order, but I don't think anything off-the-shelf from itertools would accomplish that. You'd need to write your own loops to do it. It's probably not worth it unless `arr` is large enough for the sort time to be problematic. You could also write a generator to produce the pairs in the desired order. – Tom Karzes May 24 '19 at 10:18

1 Answers1

0

You can probably use your own modified approach to achieve this in one go.

sorted([(x, y) for x in [1, 2, 3] for y in [1, 2, 3]], key=lambda y:max(y))

OUTPUT

[(1, 1), (1, 2), (2, 1), (2, 2), (1, 3), (2, 3), (3, 1), (3, 2), (3, 3)]

Divyanshu Srivastava
  • 1,379
  • 11
  • 24