【问题标题】:Summing through an array containing other arrays通过包含其他数组的数组求和
【发布时间】:2021-12-10 00:36:26
【问题描述】:

我想对一个由其他子数组组成的数组求和。

import numpy as np

a1 = np.array([1,2,3])
a2 = np.array([3,4,5])
a3 = np.array([6,7,8])

a = np.concatenate(([a1],[a2],[a3]))

print(len(a))

for i in range(1,len(a)):                                 (1)
    for j in i :                                          (2)
        for k in j :                                      (3)
            goal = np.sum(np.cos(k))
        print(goal)
        
   
        
goal  to achieve  : 

    goal = cos(1)+cos(2)+cos(3) 
    goal = cos(3)+cos(4)+cos(5) 
    goal = cos(6)+cos(7)+cos(8)

我想先在包含所有其他子数组 (1) 的数组上循环,然后循环每个子数组 (2),最后在每个子数组 (3) 内循环。

我会得到回溯:

File "*****************", line 18, in <module>
    for j in i :

TypeError: 'int' object is not iterable

在我真正的问题中,我可能有超过 3 个子数组。我认为可以做到,但我仍在探索 Python。

【问题讨论】:

    标签: python numpy loops for-loop


    【解决方案1】:

    你有太多的循环级别。您只需要一个循环来遍历数组的行,然后就可以对该行求和。

    for row in a:
        goal = np.sum(np.cos(row))
        print(goal)
    

    【讨论】:

    • np.sum 采用轴参数,该参数比在行上循环要快得多
    • @PranavHosangadi 我怀疑有一个 numpy 单行,但我不太了解 numpy。我建议您发布该答案。
    • 简单、直接。非常感谢您的回答!
    【解决方案2】:
    In [212]: a1 = np.array([1,2,3])
         ...: a2 = np.array([3,4,5])
         ...: a3 = np.array([6,7,8])
         ...: 
         ...: a = np.concatenate(([a1],[a2],[a3]))
         ...: 
    

    生成的二维数组:

    In [213]: a
    Out[213]: 
    array([[1, 2, 3],
           [3, 4, 5],
           [6, 7, 8]])
    

    每个元素的cos:

    In [214]: np.cos(a)
    Out[214]: 
    array([[ 0.54030231, -0.41614684, -0.9899925 ],
           [-0.9899925 , -0.65364362,  0.28366219],
           [ 0.96017029,  0.75390225, -0.14550003]])
    

    总和:

    In [215]: np.cos(a).sum(axis=1)
    Out[215]: array([-0.86583703, -1.35997393,  1.56857251])
    

    更容易验证这是对行求和:

    In [216]: a.sum(axis=1)
    Out[216]: array([ 6, 12, 21])
    

    对于numpy,最好考虑整个多维数组,以及对整个事物或特定维度起作用的操作。这既更快又通常更有用。

    【讨论】:

    • 非常感谢您的解释,我开始了解 numpy 是如何工作的。
    【解决方案3】:

    而不是j in ij in a[i]

    【讨论】:

    • 你在哪里打电话np.cos()
    • 他不想要一切的总和。他想要每一行的余弦之和。
    • 哦,所以当你尝试 cos 并且列表有另一个列表时出现问题?
    • 阅读问题中“要实现的目标”之后的部分
    • 现在我明白了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多