Nikita Gupta Nikita Gupta - 1 month ago 10
Python Question

Python,merge two arrays

Merge two arrays in Python as shown below:

A=[[1,2,3],[3,4,5],[6,7,8],[9,10,11]]

B=[0,1,1,1]


Expected Output:

C=[[[1,2,3],[0]],[[1,2,3],[1]],[[1,2,3],[1]],[[1,2,3],[1]]]


Tried:

zip

Answer

You already have answers to achieve this using list comprehension. You may achieve it with zip() as well, if you use it in right way as:

  • using map(zip()) combination as:

    >>> list(map(lambda x: [A[0], [x]], B))
    [[[1, 2, 3], [0]], [[1, 2, 3], [1]], [[1, 2, 3], [1]], [[1, 2, 3], [1]]]
    
  • using zip(map()) combination as:

    >>> zip([A[0]]*4, map(lambda x: [x], B))
    [([1, 2, 3], [0]), ([1, 2, 3], [1]), ([1, 2, 3], [1]), ([1, 2, 3], [1])]
    

    Explanation: Here map() will convert your list B to:

    >>> map(lambda x: [x], B)
    [[0], [1], [1], [1]]
    

    and [A[0]]*4 will create new list with copies of A[0] as:

    >>> [A[0]]*4
    [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
    

    Now you need to just zip() the both lists.

`