0

For my application scope, I need to concatenate two one-dimension array into one multi-dimension array, both implemented using (eventually nested) lists in Python. The concatenations have to print all the possible combinations between the elements of the first array with the elements of the second array.

vectA=[124,172,222,272,323,376,426,479,531]
vectB=[440,388,336,289,243,197,156,113,74]

The expected result is a multi-dimension array with the combinations of vectA with all the elements of vectB (cartesian product).

output=[[124,440],[124,388],[124,336],[124,289]...[172,440],[172,388]...]
norok2
  • 25,683
  • 4
  • 73
  • 99
Minez97
  • 65
  • 9
  • 1
    Hello and welcome to SO. What have you tried that didn't work ? This is actually a very very simple thing to do, so I'm not sure I understand what your problem is... – bruno desthuilliers Feb 18 '19 at 08:50
  • https://stackoverflow.com/questions/21260244/create-array-from-two-arrays-in-python – mTv Feb 18 '19 at 08:53
  • Typically, in Python these are referred to as `list` and not `arrays`. Please have a look at `numpy` for a performant and *de facto* standard library for array manipulation in Python. – norok2 Feb 18 '19 at 09:35
  • Possible duplicate of [How to merge lists into a list of tuples?](https://stackoverflow.com/questions/2407398/how-to-merge-lists-into-a-list-of-tuples) – norok2 Feb 18 '19 at 09:39

2 Answers2

1

use itertools.product:

from itertools import product

vectA=[124,172,222,272,323,376,426,479,531]
vectB=[440,388,336,289,243,197,156,113,74]

output = list(product(vectA,vectB))
output = [list(i) for i in output]
print(output)
Sociopath
  • 13,068
  • 19
  • 47
  • 75
1

No need to import a package here.

You can do this with simple list comprehensions, too:

vectA = [124, 172, 222, 272, 323, 376, 426, 479, 531]
vectB = [440, 388, 336, 289, 243, 197, 156, 113, 74]

output = [[a, b] for a in vectA for b in vectB]
print(output)

Also, I would propose to output a list of tuples instead of a list of lists:

output = [(a, b) for a in vectA for b in vectB]

giving you: [(124, 440), (124, 388), (124, 336), ... , (531, 74)]

Using tuples would, in my opinion, more clearly convey to someone else your intention of pairing all the values of vectA with all the values of vectB.

You can still do e.g. output[0] to get (124, 440) and output[0][0] to get 124 as you would with a list of lists.

Note though, that you can not overwrite the values of a tuple like you could with values of a list, since tuples are immutable.

poehls
  • 36
  • 4