【问题标题】:Find the sum of two lists of lists element-wise [closed]按元素查找两个列表列表的总和[关闭]
【发布时间】:2020-01-21 05:25:50
【问题描述】:

我有两个列表列表,我想从两个列表元素中找到总和

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

结果应该是[11, 4, 6], [15, 10, 12]
目前,我有

for i in len(list1):
    sum = list1[i] + list2[i]
print(sum)

但它给了我错误的结果。

【问题讨论】:

    标签: python list nested sum


    【解决方案1】:

    你可以直接使用zip

    >>> list1
    [[1, 2, 3], [4, 5, 6]]
    >>> list2
    [[10, 2, 3], [11, 5, 6]]
    >>> [[x+y for x,y in zip(l1, l2)] for l1,l2 in zip(list1,list2)]
    [[11, 4, 6], [15, 10, 12]]
    

    或者如果您不确定,如果两个列表的长度相同,那么您可以使用itertools 中的zip_longest(python2 中的izip_longest)并使用fillvalue 之类的,

    >>> import itertools
    >>> y = itertools.zip_longest([1,2], [3,4,5], fillvalue=0)
    >>> list(y)
    [(1, 3), (2, 4), (0, 5)]
    

    然后您可以将它用于大小不等的数据,例如,

    >>> from itertools import zip_longest
    >>> list1=[[1, 2, 3], [4, 5]]
    >>> list2=[[10, 2, 3], [11, 5, 6], [1,2,3]]
    >>> [[x+y for x,y in zip_longest(l1, l2, fillvalue=0)] for l1,l2 in zip_longest(list1,list2, fillvalue=[])]
    [[11, 4, 6], [15, 10, 6], [1, 2, 3]]
    

    【讨论】:

      【解决方案2】:

      在 Python 中,很少需要使用索引,尤其是对于像这样的任务,您希望单独对每个元素执行相同的操作。这种转换的主要功能是map,列表推导提供了一种方便的速记。然而,map 做了一件没有做的事情——并行处理多个迭代,就像 Haskell 的zipWith。我们可以将其分解为两个阶段:

      list1 = [[1, 2, 3], [4, 5, 6]]
      list2 = [[10, 2, 3], [11, 5, 6]]
      from operator import add
      def addvectors(a, b):
          return list(map(add, a, b))
      list3 = list(map(addvectors, list1, list2))
      

      在 Python 2 中,map 返回一个列表,因此您不需要像我在此处对 list 所做的那样单独收集它。

      【讨论】:

        【解决方案3】:

        您可以为此使用 numpy:

        import numpy as np
        list1=[[1, 2, 3], [4, 5, 6]]
        list2=[[10, 2, 3], [11, 5, 6]]
        list1_np = np.asarray(list1)
        list2_np = np.asarray(list2)
        total = list1_np + list2_np
        print(total)
        

        [[11 4 6] [15 10 12]]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-08
          • 1970-01-01
          • 2021-01-01
          • 2022-07-07
          • 1970-01-01
          • 2018-10-21
          相关资源
          最近更新 更多