简体   繁体   English

如何对 Python 中的二维数组求和?

[英]How to sum a 2d array in Python?

I want to sum a 2 dimensional array in python:我想在 python 中求和一个二维数组:

Here is what I have:这是我所拥有的:

def sum1(input):
    sum = 0
    for row in range (len(input)-1):
        for col in range(len(input[0])-1):
            sum = sum + input[row][col]

    return sum


print sum1([[1, 2],[3, 4],[5, 6]])

It displays 4 instead of 21 (1+2+3+4+5+6 = 21).它显示4而不是21 (1+2+3+4+5+6 = 21)。 Where is my mistake?我的错误在哪里?

I think this is better: 我认为这更好:

 >>> x=[[1, 2],[3, 4],[5, 6]]                                                   
>>> sum(sum(x,[]))                                                             
21

You could rewrite that function as, 你可以重写那个函数,

def sum1(input):
    return sum(map(sum, input))

Basically, map(sum, input) will return a list with the sums across all your rows, then, the outer most sum will add up that list. 基本上, map(sum, input)将返回一个列表,其中包含所有行的总和,然后,最外层的sum将添加该列表。

Example: 例:

>>> a=[[1,2],[3,4]]
>>> sum(map(sum, a))
10

Better still, forget the index counters and just iterate over the items themselves: 更好的是,忘记索引计数器,只是迭代项目本身:

def sum1(input):
    my_sum = 0
    for row in input:
        my_sum += sum(row)
    return my_sum

print sum1([[1, 2],[3, 4],[5, 6]])

One of the nice (and idiomatic) features of Python is letting it do the counting for you. Python的一个很好的(和惯用的)功能是让它为你做计数。 sum() is a built-in and you should not use names of built-ins for your own identifiers. sum()是内置函数,您不应该使用内置函数的名称作为您自己的标识符。

This is yet another alternate Solution 这是另一种替代解决方案

In [1]: a=[[1, 2],[3, 4],[5, 6]]
In [2]: sum([sum(i) for i in a])
Out[2]: 21

This is the issue 这是问题所在

for row in range (len(input)-1):
    for col in range(len(input[0])-1):

try 尝试

for row in range (len(input)):
    for col in range(len(input[0])):

Python's range(x) goes from 0..x-1 already Python的范围(x)已经从0..x-1开始

range(...) range([start,] stop[, step]) -> list of integers range(...)range([start,] stop [,step]) - >整数列表

 Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. 

And numpy solution is just: numpy解决方案只是:

import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])

Result: 结果:

>>> b=np.sum(x)
   print(b)
21

range() in python excludes the last element. python中的range()排除了最后一个元素。 In other words, range(1, 5) is [1, 5) or [1, 4]. 换句话说, range(1, 5)是[1,5]或[1,4]。 So you should just use len(input) to iterate over the rows/columns. 所以你应该使用len(input)迭代行/列。

def sum1(input):
    sum = 0
    for row in range (len(input)):
        for col in range(len(input[0])):
            sum = sum + input[row][col]

    return sum

Don't put -1 in range(len(input)-1) instead use: 不要将-1放在范围内(len(输入)-1)而是使用:

range(len(input))

range automatically returns a list one less than the argument value so no need of explicitly giving -1 range自动返回一个小于参数值的列表,因此不需要显式给出-1

Quick answer, use... 快速回答,使用......

total = sum(map(sum,[array]))

where [array] is your array title. 其中[array]是你的数组标题。

def sum1(input):
    return sum([sum(x) for x in input])

In Python 3.7 在Python 3.7中

import numpy as np
x = np.array([ [1,2], [3,4] ])
sum(sum(x))

outputs 输出

10

It seems like a general consensus is that numpy is a complicated solution.似乎普遍的共识是 numpy 是一个复杂的解决方案。 In comparison to simpler algorithms.与更简单的算法相比。 But for the sake of the answer being present:但是为了存在答案:

import numpy as np


def addarrays(arr):

    b = np.sum(arr)
    return sum(b)


array_1 = [
  [1, 2],
  [3, 4],
  [5, 6]
]
print(addarrays(array_1))

This appears to be the preferred solution:这似乎是首选的解决方案:

x=[[1, 2],[3, 4],[5, 6]]                                                   
sum(sum(x,[]))                                                             
def sum1(input):
    sum = 0
    for row in input:
        for col in row:
            sum += col
    return sum
print(sum1([[1, 2],[3, 4],[5, 6]]))

Speed comparison速度比较

import random
import timeit
import numpy
x = [[random.random() for i in range(100)] for j in range(100)]
xnp = np.array(x)

Methods方法

print("Sum python array:")
%timeit sum(map(sum,x))
%timeit sum([sum(i) for i in x])
%timeit sum(sum(x,[]))
%timeit sum([x[i][j] for i in range(100) for j in range(100)])

print("Convert to numpy, then sum:")
%timeit np.sum(np.array(x))
%timeit sum(sum(np.array(x)))

print("Sum numpy array:")
%timeit np.sum(xnp)
%timeit sum(sum(xnp))

Results结果

Sum python array:
130 µs ± 3.24 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
149 µs ± 4.16 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
3.05 ms ± 44.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Convert to numpy, then sum:
1.36 ms ± 90.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.63 ms ± 26.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Sum numpy array:
24.6 µs ± 1.95 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
301 µs ± 4.78 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

def sum1(input): sum = 0 for row in range (len(input)-1): for col in range(len(input[0])-1): sum = sum + input[row][col] def sum1(input): sum = 0 for row in range (len(input)-1): for col in range(len(input[0])-1): sum = sum + input[row][col]

return sum

print (sum1([[1, 2],[3, 4],[5, 6]])) You had a problem with parenthesis at the print command.... This solution will be good now The correct solution in Visual Studio Code print (sum1([[1, 2],[3, 4],[5, 6]]))你在打印命令时遇到了括号问题....这个解决方案现在很好Visual中的正确解决方案工作室代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM