Element-wise addition of 2 lists?

后端 未结 16 1215
感动是毒
感动是毒 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:32

    Use map with operator.add:

    >>> from operator import add
    >>> list( map(add, list1, list2) )
    [5, 7, 9]
    

    or zip with a list comprehension:

    >>> [sum(x) for x in zip(list1, list2)]
    [5, 7, 9]
    

    Timing comparisons:

    >>> list2 = [4, 5, 6]*10**5
    >>> list1 = [1, 2, 3]*10**5
    >>> %timeit from operator import add;map(add, list1, list2)
    10 loops, best of 3: 44.6 ms per loop
    >>> %timeit from itertools import izip; [a + b for a, b in izip(list1, list2)]
    10 loops, best of 3: 71 ms per loop
    >>> %timeit [a + b for a, b in zip(list1, list2)]
    10 loops, best of 3: 112 ms per loop
    >>> %timeit from itertools import izip;[sum(x) for x in izip(list1, list2)]
    1 loops, best of 3: 139 ms per loop
    >>> %timeit [sum(x) for x in zip(list1, list2)]
    1 loops, best of 3: 177 ms per loop
    

提交回复
热议问题