-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

3 Answers3

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.

  • 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 Feb 16 '16 at 19:27
  • @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. –  Feb 16 '16 at 19:28
  • 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 Feb 16 '16 at 19:29
  • 2
    @amateur_programmer so use this, and set `a` and `b` appropriately. –  Feb 16 '16 at 19:30
  • 1
    @amateur_programmer using Numpy makes this a duplicate of http://stackoverflow.com/q/11144513/1544337. –  Feb 16 '16 at 19:31
  • Is there a way to manually write the code for function itertools is performing?ex usinng for loops? i tried to do : 'for i in range (0,100): for j in range (0,100): grid[i][j]=(x[i],y[j])' – amateur_programmer Feb 16 '16 at 19:32
  • @amateur_programmer yes, see the documentation I linked to from my post. Equivalent code is provided there. –  Feb 16 '16 at 19:33
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)]
danidee
  • 9,298
  • 2
  • 35
  • 55
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))
Seekheart
  • 1,135
  • 7
  • 8