如何在最简洁的 python 中对多维数组求和?

2022-11-06Python开发问题
49

本文介绍了如何在最简洁的 python 中对多维数组求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

最接近的是这个汇总列.

所以我会在我的问题中做类似的事情:

So I'll do something similar in my question:

假设我有一个 Python 2D 列表,如下所示:

Say I've a Python 2D list as below:

my_list =  [ [1,2,3,4],
             [2,4,5,6] ]

我可以通过列表理解获得行总数:

I can get the row totals with a list comprehension:

row_totals = [ sum(x) for x in my_list ]

如何在一行中求和整个二维数组?

In one line, how can I sum the entire 2d-array?

27

推荐答案

你可以做到这么简单

sum(map(sum, my_list))

或者

sum(sum(x) for x in my_list))

如果您不期望超过 2 个维度,那就收工吧.请注意,由于 map() 的使用,第一个解决方案很可能不是最快的(如执行时间)解决方案.必要时进行基准测试和比较.

and call it a day, if you don't expect more than 2 dimensions. Note that the first solution is most likely not the fastest (as in execution time) solution, due to the usage of map(). Benchmark and compare as necessary.

最后,如果您发现自己使用多维数组,请考虑使用 NumPy 及其优越的数组友好函数.以下是您的问题的简短摘录:

Finally, if you find yourself using multidimensional arrays, consider using NumPy and its superior array-friendly functions. Here's a short excerpt for your problem:

import numpy as np

my_list = np.array([[1,2,3,4], [2,4,5,6]])
np.sum(my_list)

这适用于您的数组可能具有的任意数量的维度.

This would work for any number of dimensions your arrays might have.

这篇关于如何在最简洁的 python 中对多维数组求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11