Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate array of number pairs from 2 numpy vectors [duplicate]

Is there an easy way in Numpy to generate an array of number pairs from 2 1D numpy arrays (vectors) without looping?

input:

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

output:

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

I wondering if there is a function that does something similar to this:

c = []
for i in range(len(a)):
    for j in range(len(b)):
        c.append((a[i], b[j]))
like image 627
marillion Avatar asked Feb 08 '14 21:02

marillion


1 Answers

You can use itertools.product for this:

from itertools import product

c = list(product(a, b))

This gives:

c == [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
like image 138
jonrsharpe Avatar answered Oct 10 '22 13:10

jonrsharpe