Question

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]))
Was it helpful?

Solution

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)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top