I want to combine two 2d-arrays into one NX2 array, but I don't know what command should I use in python.
For example, a = [1.2.3] b = [4,5,6], and I want to have a new array which have the elements in a as the x-coordinate and b as the y-coordinate, c = [(1,4)],(2,5),(3,6)]
Any hint for this in python language?
You're lucky, because Python has a built-in zip function that does exactly what you want.
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> zip(a, b)
[(1, 4), (2, 5), (3, 6)]
Note that in Python 3, zip returns an iterator, not a list, so you will have to use list(zip(a, b)) to get a list.
Also note that zip truncates the length of the result to the smallest list.
For example:
>>> zip([1, 2], [3, 4, 5])
[(1, 3), (2, 4)]
You can combat this with itertools.izip_longest (or itertools.zip_longest in Python 3).
>>> import itertools
>>> list(itertools.izip_longest([1, 2], [3, 4, 5], fillvalue=0))
[(1, 3), (2, 4), (0, 5)]
This will use the fillvalue to fill in the empty gaps. By default, fillvalue is set to None.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With