【问题标题】:python: pointwise list sumpython:逐点列表总和
【发布时间】:2011-04-26 09:34:14
【问题描述】:
Input: two lists (list1, list2) of equal length
Output: one list (result) of the same length, such that:
    result[i] = list1[i] + list2[i]

有什么简洁的方法可以做到这一点吗?或者这是最好的:

# Python 3
assert len(list1) == len(list2)
result = [list1[i] + list2[i] for i in range(len(list1))]

【问题讨论】:

  • 我最初将其读作“毫无意义的明智之和”。我想我可能需要睡觉了。

标签: python list


【解决方案1】:

您可以使用内置的zip 函数,也可以使用do it 将两个列表映射到add 运算符。像这样:

from operator import add
map(add, list1,list2)

【讨论】:

  • +1 不知道map 可以接受多个迭代。绝对比我的回答好:)
【解决方案2】:

IMO 最好的方法是

result = [x + y for x, y in zip(list1, list2)]

使用 Python3 基本 zip 甚至没有构建中间列表(除非 list1list2 列表很大,否则这不是问题)。

但请注意,zip 将停在输入列表中最短的位置,因此仍然需要您的 assert

【讨论】:

    【解决方案3】:
    [a + b for a, b in zip(list1, list2)]
    

    【讨论】:

      【解决方案4】:

      有几种方法,例如使用mapsumizip(但是afaik,zip 与 Python 3 中的izip 工作方式相同):

      >>> from itertools import izip
      >>> map(sum, izip(list1, list2))
      

      【讨论】:

        【解决方案5】:

        我愿意:

        result = [x+x for x,y in zip(list1, list2)]
        

        【讨论】:

        • 你的意思是x + y
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-15
        • 2023-01-12
        • 1970-01-01
        • 1970-01-01
        • 2013-04-18
        相关资源
        最近更新 更多