-2

Lets say you have an multidimensional array

a = np.array([[1, 2], [3, 5], [4,5], [9,5]])

I want all the possible combinations of two arrays given the multidimensional array "a" so that:

[[1, 2],[3, 5]] , [[1, 2],[4,5]] ... 

I have no idea how to due this. Does someone have some suggestions and tips?

Mathomat55
  • 109
  • 5
  • 1
    can you show us what you tried? – OrenIshShalom Sep 20 '22 at 16:16
  • 4
    Sure is useful that [`itertools.combinations`](https://docs.python.org/3/library/itertools.html#itertools.combinations) exists. – kelsny Sep 20 '22 at 16:18
  • 1
    Your question is similar to this https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements you can replace just normal list elements with your sublists and the logic is the same. – JRose Sep 20 '22 at 16:21
  • @OrenIshShalom I have tried to use np.mgrid, but I didn't really understand how to us it and if it could be applied in this context. I forgot to mention that I am only allowed to use simple packages like numpy :( – Mathomat55 Sep 20 '22 at 16:21
  • `itertools` is in the standard library and is for sure 'simpler' than NumPy. (It's hard to think of a less simple library than NumPy...) – Matt Hall Sep 20 '22 at 16:29
  • @kwinkunks Ok, I will try to use that library then :) Thank you! – Mathomat55 Sep 20 '22 at 16:31
  • is: ````([1, 2], [3, 5]),... ([3, 5], [1, 2]),...]```` seen as an unnecessary duplicate, or is this ok? – lroth Sep 20 '22 at 18:26

1 Answers1

0

You can use itertools.combinations function defined in this answer. This code creates the list of all the combinations.

import numpy as np
import itertools

a = np.array([[1, 2], [3, 5], [4,5], [9,5]])
combination=[]  

for L in range(len(a) + 1):
    for subset in itertools.combinations(a, L):
        combination.append([list(sub) for sub in subset])
combination