Element-wise product of two 2-D lists

前端 未结 4 1733
[愿得一人]
[愿得一人] 2021-01-21 05:06

I can\'t use Numpy or any other library function as this is a question I have to do, I have to define my own way.

I am writing a function that takes two lists (2 dimensi

4条回答
  •  面向向阳花
    2021-01-21 05:55

    You can zip the two lists in a list comprehension, then further zip the resulting sublists and then finally multiply the items:

    list2 = [[5,2,9,3,7],[1,3,5,2,2]]
    list1 = [[2,3,5,6,7],[5,2,9,3,7]]
    
    result = [[a*b for a, b in zip(i, j)] for i, j in zip(list1, list2)]
    print(result)
    # [[10, 6, 45, 18, 49], [5, 6, 45, 6, 14]]
    

    Should in case the lists/sublists do not have the same number of elements, itertools.izip_longest can be used to generate fill values such as an empty sublist for the smaller list, or 0 for the shorter sublist:

    from itertools import izip_longest
    
    list1 = [[2,3,5,6]]
    list2 = [[5,2,9,3,7],[1,3,5,2,2]]
    result = [[a*b for a, b in izip_longest(i, j, fillvalue=0)] 
                   for i, j in izip_longest(list1, list2, fillvalue=[])]
    print(result)
    # [[10, 6, 45, 18, 0], [0, 0, 0, 0, 0]]
    

    You may change the inner fillvalue from 0 to 1 to return the elements in the longer sublists as is, instead of a homogeneous 0.


    Reference:

    List comprehensions

提交回复
热议问题