Element-wise addition of 2 lists?

后端 未结 16 1415
感动是毒
感动是毒 2020-11-22 07:48

I have now:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

I wish to have:

[1, 2, 3]
 +  +  +         


        
16条回答
  •  自闭症患者
    2020-11-22 08:44

    • The zip function is useful here, used with a list comprehension v1, v2.
    • If you have a list of lists (instead of just two lists) you can use v3.
    • For lists with different length (for example: By adding 1 to the end of the first/secound list), then you can try something like this (using zip_longest) - v4
    first = [1, 2, 3, 1]
    second = [4, 5, 6]
    
    output: [5, 7, 9, 1]
    
    • If you have an unknown number of lists of the same length, you can use the function v5.

    • v6 - The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y.

    • v7 - Assuming both lists first and second have same length, you do not need zip or anything else.

    ################
    first = [1, 2, 3]
    second = [4, 5, 6]
    
    ####### v1 ########
    third1 = [sum(i) for i in zip(first,second)]
    
    ####### v2 ########
    third2 = [x + y for x, y in zip(first, second)]
    
    ####### v3 ########
    lists_of_lists = [[1, 2, 3], [4, 5, 6]]
    third3 = [sum(x) for x in zip(*lists_of_lists)]
    
    ####### v4 ########
    from itertools import zip_longest
    third4 = list(map(sum, zip_longest(first, second, fillvalue=0)))
    
    ####### v5 ########
    def sum_lists(*args):
        return list(map(sum, zip(*args)))
    
    third5 = sum_lists(first, second)
    
    ####### v6 ########
    import operator
    third6 = list(map(operator.add, first,second))
    
    ####### v7 ########
    third7 =[first[i]+second[i] for i in range(len(first))]
    
    ####### v(i) ########
    
    print(third1) # [5, 7, 9]
    print(third2) # [5, 7, 9]
    print(third3) # [5, 7, 9]
    print(third4) # [5, 7, 9]
    print(third5) # [5, 7, 9]
    print(third6) # [5, 7, 9]
    print(third7) # [5, 7, 9]
    

提交回复
热议问题