python - 无需 for 循环即可对数组元素进行运算

标签 python arrays python-3.x numpy optimization

我遇到这个问题,我需要获取数组的一个元素,使该元素与索引较高的元素之间的总和分别。我已经用 for 循环完成了此操作,例如:

sumtot = np.array([])
for j in range(0,len(matpos)-1):
    sum = matpos[j] + matpos[j+1:]
    sumtot = np.append(sumtot, sum)

但这需要大量的计算时间,因为数组 matpos 是一个非常大的数组,所以我想是否有一种方法可以在不使用 for 循环的情况下完成此操作.

一个简单的示例是:

-输入:

matpos = np.array([0, 1, 2, 3])

-输出

sumtot = np.array([1, 2, 3, 3, 4, 5])

这是[0+1, 0+2, 0+3, 1+2, 1+3, 2+3]

非常感谢大家!

最佳答案

要获取所需的数组,您可以使用类似 np.triu_indices 的内容进行一些额外的操作:

r, c = np.triu_indices(len(matpos), 1)
totsum = matpos[r] + matpos[c]

这可能是您所能理解的最清晰的内容。如果您想要一行,您可以堆叠索引并将结果相加:

totsum = matpos[np.stack(np.triu_indices(len(matpos), 1))].sum(0)

请注意,这些术语的总结如下:

 [matpos[0], matpos[0], matpos[0], ...] + [matpos[1], matpos[2], matpos[3], ...]
 [matpos[1], matpos[1], ...] + [matpos[2], matpos[3], ...]
 [matpos[2], ...] + [matpos[3], ...]

所选索引和重复次数与triu_indices(列减一)的结果完全对应,该结果返回矩阵上三角形的索引。

另一种表述:

r, c = np.triu_indices(len(matpos) - 1)
totsum = matpos[r] + matpos[c + 1]

或者

totsum = matpos[np.stack(np.triu_indices(len(matpos) - 1), -1) + [0, 1]].sum(1)

关于python - 无需 for 循环即可对数组元素进行运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66125483/

相关文章:

JavaScript 打印整个数组而不是单个元素

excel - 单个 Excel 工作表中的多个 NamedStyle - Python openpyxl

python-3.x - 是否有一个函数可以查找列表中哪些 float 加起来等于特定间隔内的数字?

python - 类型错误 : 'NoneType' object has no attribute '__getitem__' in python code which uses google API

python - 将元素列表分配到具有不同排除项的 3 个列表中

javascript - 如何通知客户端浏览器有关服务器上的某些事件?

python - 如何解压嵌套列表的内部列表?

python - 不要在 2D 热图上显示零值

arrays - 在 go 中解码 xml 时省略空数组元素

复制 C 中的字符串数组错误