【问题标题】:Summing nested arrays of different length in python在python中对不同长度的嵌套数组求和
【发布时间】:2020-03-23 09:41:51
【问题描述】:

我有数组 p1 和 p2,它们看起来都像

array([  1.00000000e+00,   4.00000000e+00,   8.90000000e+01,
         1.00000000e+00,   3.94090600e-06,   2.22958010e-02,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00])

array([  1.00000000e+00,   4.00000000e+00,   8.90000000e+01,
         1.00000000e+00,   3.94090600e-06,   2.87729900e-03,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00])

所以 p2 比 p1 长。请注意,数字本身并不重要。

他们在列表中

p = [p1,p2]

我想对它们求和,这样 p2 中的额外值就会被截断。我以为我能做到

sum(p[:][0:10])

但这会产生操作数错误。实际上,我真的不确定我是否理解 sum 函数在这种情况下试图做什么。我知道它在 p1 和 p2 长度相同的情况下有效。

基本上我想要的结果

p[0][0:10]+p[1][0:10]

给,即

array([  2.00000000e+00,   8.00000000e+00,   1.78000000e+02,
         2.00000000e+00,   7.88181200e-06,   2.51731000e-02,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00])

我想出了一个解决方法,但它很恶心,我觉得可能有一种方法可以让 sum 函数做到这一点。

【问题讨论】:

    标签: arrays nested sum


    【解决方案1】:

    您不能直接使用 sum 来执行此操作。 sum 基本上只是遍历一个列表并汇总元素,如

    def sum(iterables):
      total = 0
      for elem in iterables: total += elem
      return total
    

    您可以使用列表理解来实现您的目标,如下所示

    # Find out the minimum length of list inside p to truncate excess elements
    truncated_len = min([len(list) for list in p])
    # Sum up each elements
    result = [sum([p[j][i] for j in range(len(p))]) for i in range(truncated_len)]
    print(result)
    

    【讨论】:

    • 谢谢,不幸的是,这会产生与仅使用 sum 相同的操作数错误。我将坚持使用我的解决方法,将数组逐行复制到新的数据结构中。不完全优雅,但它有效。
    猜你喜欢
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2013-10-20
    • 2015-03-24
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多