'How create a ordered pair function in Python?

I come from Matlab and I want code a function to create a ordered pair function.

example:

Array1=[2,5,7]; Array2 = [6,2];

PairOrdered = [ 2,6 ; 2,2 ; 5,6 ; 5,2 ; 7,6 ; 7,2];

In Matlab I use this logic:

LA=length(A);
LB=length(B);
LT= LA*LB;

M = zeros(LT,2);

for i = 1:LA

for j =1:LB

    M((i-1)*LB+j , : ) = [A(i),B(j)];

end
end

As you can see, I define a pair ordered matrix with the length of the two arrays. In Python I use the same logic like this:

A = [1,2,3,4];
B = [5,6,7];

LA = len(A)
LB = len(B)

Maux = [];

for i in A:
for j in B:

    Maux[(i-1)*LB+j , j]

The system say this:

Traceback (most recent call last): File "C:\Users---\Desktop\Code1\ParOrde.py", line 17, in Maux[(i-1)*LB+j , j] TypeError: list indices must be integers or slices, not tuple

How I can create a dynamic matrix type integers? Or how I fix this?



Solution 1:[1]

The thing you are looking for is itertools.product() to give you the product of those two lists:

import itertools
Array1 = [2,5,7]
Array2 = [6,2]
Array1_Array2 = list(itertools.product(Array1, Array2))
print(Array1_Array2)

If you were keen on doing it yourself you might use a comprehension:

Array1 = [2,5,7]
Array2 = [6,2]
Array1_Array2 = [(a, b) for a in Array1 for b in Array2]
print(Array1_Array2)

or via traditional for loops:

Array1 = [2,5,7]
Array2 = [6,2]
Array1_Array2 = []
for a in Array1:
    for b in Array2:
        Array1_Array2.append((a,b))
print(Array1_Array2)

All three will give you a list of tuples:

[(2, 6), (2, 2), (5, 6), (5, 2), (7, 6), (7, 2)]

Though casting the tuples themselves to lists is trivial if you wanted that.

If you are going to be doing a munch of "matrix" like stuff, you might want to check out the numpy package.

Implemented as a function, it might look like:

def OrderPair(A,B):
    return [[a, b] for a in A for b in B]

A1 = [2,5,7]
A2 = [6,2]
S = OrderPair(A1, A2)
print(S)

Giving you:

[[2, 6], [2, 2], [5, 6], [5, 2], [7, 6], [7, 2]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1