Nikita Gupta Nikita Gupta - 29 days ago 8
Python Question

How to merge a list with a list of lists

How to merge two lists (one a list of lists) in Python?

Input:

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

B = [0,1,1,1]


Desired output:

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


I 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.

`

Comments