Python-按元素添加2个列表?

发布于 2021-02-02 23:17:16

我现在有了:

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

我希望有:

[1, 2, 3]
 +  +  +
[4, 5, 6]
|| || ||
[5, 7, 9]

只是两个列表的元素加法。

我当然可以迭代两个列表,但是我不想这样做。

什么是最Python的方式这样做的?

关注者
0
被浏览
66
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    使用map有operator.add

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

    或zip具有列表理解:

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

    时序比较:

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看