Reputation: 67
For my application scope, I need to concatenate two one-dimension array into one multi-dimension array, both implemented using (eventually nested) list
s 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]...]
Upvotes: 0
Views: 592
Reputation: 36
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.
Upvotes: 1
Reputation: 13426
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)
Upvotes: 1