-3

I want to merge two arrays in python with all possible combinations

ex a= [1, 2, 3] and b= [4, 5, 6] should give the output

c= [(1,4),(1,5),(1,6)  
   (2,4),(2,5),(2,6)  
   (3,4),(3,5),(3,6)]

in this particular order(i.e. of order 3x3). The order is particularly important here

0

3 Answers 3

10

The itertools.product function does exactly this.

>>> import itertools
>>> a, b = [1,2,3], [4,5,6]
>>> list(itertools.product(a, b))
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

Note: it might very well be the case that you don't need list(), this is just to show the output here.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you camil. But I posted that as an example. How do you do it for several elements ? My original array has 100 elements each
@amateur_programmer you have 100 lists of 100 elements that you want to 'merge'? Or two lists of 100 elements? In either case you can simply add more arguments to the function.
I have 2 lists of 100 elements each and I want to merge them will all possible combinations..Sorry i didn't mention it before but only by using numpy
@amateur_programmer so use this, and set a and b appropriately.
@amateur_programmer using Numpy makes this a duplicate of stackoverflow.com/q/11144513/1544337.
|
1

You're looking for itertools.product

from itertools import product

a = [1,2,3]
b = [4,5,6]

print(list(product(a, b)))

Outputs

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

Comments

0

This will return a list with all permutations of list a and b.

import itertools
map(''.join, itertools.chain(itertools.product(a, b), itertools.product(b, a))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.