3

I am struggling to combine the values of two arrays in Python. I want to get the values of two arrays as pairs.
EXAMPLE: Suppose we have two arrays a and b as below:

a = [[1, 2, 3], [4, 5, 6], [0, 3, 1]]
for i in range(len(a)):
    for j in range(len(a[i])):
        print(a[i][j], end=' ')
    print() 

b = [[4, 0, 3], [6, 3, 6], [1, 4, 1]]

for i in range(len(b)):
    for j in range(len(b[i])):
        print(b[i][j], end=' ')
    print()

How can I combine the values of two arrays as pairs similar to:

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

I am not sure if it can be done as an array or a list.

Mr. T
  • 11,960
  • 10
  • 32
  • 54
Noor
  • 365
  • 2
  • 13

1 Answers1

2

You can combine list comprehension and zip() to do that:

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

c = [ list(zip(a[x],b[x])) for x in range(len(a))] # works b/c len(a) = len(b)

print(c)

Output

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

This works correctly as a and b have the same amount of inner lists and the inner lists have the same length. zip() does only create tuples for 2 lists up to the shorter length of both. For inequeal length lists you can use itertools.zip_longest(...) which uses None or a specified default to fill up the shorter list.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69