【问题标题】:Element-wise sum of lists within lists of lists in PythonPython 列表列表中的列表元素总和
【发布时间】:2023-01-12 19:32:13
【问题描述】:

我正在使用 Python,我想对 3 个列表列表中的每个列表进行逐元素求和。我将尝试简化问题以更好地解释。

输入:

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[11,12,13],[14,15,16],[17,18,19]]
c = [[21,22,23],[24,25,26],[27,28,29]]

我需要的结果是:

d = [[1,2,3,11,12,13,21,22,23],[4,5,6,14,15,16],[7,8,9,17,18,19,27,28,29]]

请记住,我实际上拥有的列表列表具有相同的大小,但其中的单个列表却不同。

我试过的是:

d = []
for x in a:
    y = [a[x] + b[x] + c[x]]
    d.append(y)

但是我收到错误“TypeError:列表索引必须是整数或切片,而不是列表”,因为 x 被定义为等于 [1,2,3] 的列表

【问题讨论】:

    标签: python list


    【解决方案1】:

    是的,您可以在d 中“添加”子列表以形成新列表:

    a = [[1,2,3], [4,5,6], [7,8,9]]
    b = [[11,12,13], [14,15,16], [17,18,19]]
    c = [[21,22,23], [24,25,26], [27,28,29]]
    
    d = []
    for a_i,b_i,c_i in zip(a,b,c):
        d.append(a_i + b_i + c_i)
    
    print(d)
    

    按要求输出。

    事实上,你可以使用内置的sum()

    d = []
    for items in zip(a, b, c):
        d.append(sum(items, start=[]))
    
    print(d)
    

    【讨论】:

      【解决方案2】:
      import numpy as np
      
      a = np.array([[1,2,3],[4,5,6],[7,8,9]])
      b = np.array([[11,12,13],[14,15,16],[17,18,19]])
      c = np.array([[21,22,23],[24,25,26],[27,28,29]])
      
      d = np.concatenate([a, b, c], axis=1)
      
      print(d)
      #[[ 1  2  3 11 12 13 21 22 23]
       [ 4  5  6 14 15 16 24 25 26]
       [ 7  8  9 17 18 19 27 28 29]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-22
        • 1970-01-01
        相关资源
        最近更新 更多