Search code examples
pythonpython-3.4

How to merge two arrays together, concatenating the corresponding elements?


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

I'm not asking about the easy merging of array like c = a+b (which would yield [1,2,3,4,5,6].

What I am looking for is to join the contents of two arrays, so that the end-result would be as the following (given a and b written previously).

c = what-do-I-write-here? # [14,25,36]

How do I solve this?


Solution

  • Introduction

    You can zip together your two lists, forming a new lists that will contain two-element tuples (pairs), where each pair consists of the elements at the corresponding index, from the two lists.

    Python 3.5.0 (default, Sep 20 2015, 11:28:25)
    [GCC 5.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> a = [1, 2, 3]
    >>> b = [4, 5, 6]
    >>> list (zip (a,b))
    [(1, 4), (2, 5), (3, 6)]
    

    This in turn will make it very easy to iterate over each pair, and create a new list with the desired contents.


    Sample Implementation

    In your question you have written that the result should be [14,25,36] — implying that you are looking to concatenate the elements lexiographically, but then have the result still be ints.

    You could solve it in a easy manner using code such as;

    a = [1, 2, 3]
    b = [4, 5, 6]
    c = [ int(''.join (map (str, xs))) for xs in zip (a,b) ]
    
    c is now [14, 25, 36]