Element-wise product of two 2-D lists

前端 未结 4 1732
[愿得一人]
[愿得一人] 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:52

    In Python, it's generally better to loop directly over the items in a list, rather than looping indirectly using indices. It makes the code easier to read as well as more efficient since it avoids the tedious index arithmetic.

    Here's how to solve your problem using traditional for loops. We use the built-in zip function to iterate over two (or more) lists simultaneously.

    def elementwise_product(list1,list2):
        result = []
        for seq1, seq2 in zip(list1,list2):
            prods = []
            for u, v in zip(seq1, seq2):
                prods.append(u * v)
            result.append(prods)
        return result
    
    list1=[[2,3,5,6,7], [5,2,9,3,7]] 
    list2=[[5,2,9,3,7], [1,3,5,2,2]]
    
    print(elementwise_product(list1,list2))
    

    output

    [[10, 6, 45, 18, 49], [5, 6, 45, 6, 14]]
    

    We can use list comprehensions to make that code a lot more compact. It may seem harder to read at first, but you'll get used to list comprehensions with practice.

    def elementwise_product(list1,list2):
        return [[u*v for u, v in zip(seq1, seq2)] 
            for seq1, seq2 in zip(list1,list2)]
    

提交回复
热议问题