Offering this answer for completeness since numpy
has been discussed in another answer, and it is often useful to pair values together from higher ranked arrays.
The accepted answer works great for any sequence/array of rank 1. However, if the sequence is of multiple levels (such as a numpy
array of rank 2 or more, but also such as in a list
of list
s, or tuple
of tuple
s), one needs to iterate through each rank. Below is an example with a 2D numpy
array:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([list('abc'), list('pdq'), list('xyz')])
c = np.array([[frobnicate(aval, bval) for aval, bval in zip(arow, brow)] for arow, brow in zip(a, b)])
And the same concept will work for any set of two dimensional nested sequences of the same shape:
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [list('abc'), list('pdq'), list('xyz')]
c = [[frobnicate(aval, bval) for aval, bval in zip(arow, brow)] for arow, brow in zip(a, b)]
If one or both of the nested sequences has "holes" in it, use itertools.zip_longest
to fill in the holes (the fill value defaults to None
but can be specified):
from itertools import zip_longest as zipl
a = [[], [4, 5, 6], [7, 8, 9]] # empty list in the first row
b = [list('abc'), list('pdq'), []] # empty list in the last row
c = [[frobnicate(aval, bval) for aval, bval in zipl(arow, brow)] for arow, brow in zipl(a, b)]