1

I want to write a function that takes in a list of integers (e.g. L = [0,1,-1]) and a single integer (e.g. n = 3) and returns all of the (e.g. triplets) of that list: [0,0,0],[0,0,1],...[-1,-1,-1] of which there will be len(L)**n. If I'm committed to n=3, I could do:

np.array(np.meshgrid(L,L,L)).T.reshape(-1,3)

However, if I want to change that 3 to a different number, I would need to enter my list into meshgrid n times. Is there a slick way of doing this that will work for arbitrary n? I hope what I'm trying to do makes some sense. It seems like the sort of thing a function would already exist for, but I can't seem to find anything.

David Buck
  • 3,752
  • 35
  • 31
  • 35
cden
  • 115
  • 3

1 Answers1

1

Create a list of L repeated n times via: [L for _ in range(n)]. Then just dereference this list to the meshgrid function using the star operator. What does the star operator mean, in a function call?

n = 2
>>> np.array(np.meshgrid(*[L for _ in range(n)])).T.reshape(-1, n)
array([[ 0,  0],
       [ 0,  1],
       [ 0, -1],
       [ 1,  0],
       [ 1,  1],
       [ 1, -1],
       [-1,  0],
       [-1,  1],
       [-1, -1]])
Alexander
  • 105,104
  • 32
  • 201
  • 196