0

So I have a function that will generate a series of pairs. For this example I am using: [11,1], [9,9], [11,1] and the amount of pairs will be greater than or equal to three.

I am trying to create an array that shows every possible combination of these pairs. When I run:

import numpy as np
np.array(np.meshgrid([11,1], [9,9], [11,1])).T.reshape(-1,3)

It produces a correct output of:

array([[11,  9, 11],
       [11,  9, 11],
       [ 1,  9, 11],
       [ 1,  9, 11],
       [11,  9,  1],
       [11,  9,  1],
       [ 1,  9,  1],
       [ 1,  9,  1]])

However, since the input can vary, I'd like to store this pair information as a variable and simply plug it into a function for it to work. And no variable type that I've input into the function containing the pairs seems to output the correct information.

Any help with this would be much appreciated!

Jay Ghosh
  • 43
  • 3
  • 1
    Can you give examples of expected inputs? – Iain Shelvington Jan 05 '20 at 03:13
  • If the dimensions of your data vary, then numpy probably isn't the tool for the job. Can you share some more context for this? What is the program meant to do? – AMC Jan 05 '20 at 06:47
  • Ah darn I forgot to flag this as a duplicate of https://stackoverflow.com/q/798854/11301900. – AMC Jan 05 '20 at 06:58

2 Answers2

0

You could use a star operator to "explode" the elements of a tuple (or a list) to be served as function parameters:

import numpy as np
pairs = ([11,1], [9,9], [11,1])
res = np.array(np.meshgrid(*pairs)).T.reshape(-1,3)
print(res)
JohanC
  • 71,591
  • 8
  • 33
  • 66
0

This questions is a blatant duplicate of All combinations of a list of lists.


Let's keep things simple. There's no reason to use NumPy, plain Python lists and itertools will suffice. Tuples are meant for immutable, fixed length data, lists are mutable and have a variable length. The currently accepted answer swaps the two uses cases for seemingly no reason, so I was careful to use the appropriate data structures.

import itertools as itt

pairs = [(11, 1), (9, 9), (11, 1)]

combs = itt.product(*pairs)

print(list(combs))

Output:

[(11, 9, 11), (11, 9, 1), (11, 9, 11), (11, 9, 1), (1, 9, 11), (1, 9, 1), (1, 9, 11), (1, 9, 1)]
AMC
  • 2,642
  • 7
  • 13
  • 35