English 中文(简体)
如何对 Python 中的 2D 数组进行比较?
原标题:How to sum a 2d array in Python?
  • 时间:2012-05-23 03:43:01
  •  标签:
  • python

< 加强> 我想在 python 中计算一个 2 维数组 :

这就是我有的:

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]])

它显示 4 , 而不是 >21 (1+2+3+4+5+6=21)。 我的错误在哪里?

最佳回答

问题就在于此

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

试试

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

Python s 范围(x) 已经从 0. x-1 开始

range(...) range([start,] stop[, step]) -> list of integers

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.
问题回答

我觉得这样更好:

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

您可以将此函数重写为 :

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

基本上, map( 和, 输入) 将返回一个列表, 包含您所有行的总和, 那么, 最外在的 < code> sum 将添加到列表中 。

示例:

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

这是另一个替代解决方案

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

营养问题的解决办法是:

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

结果:

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

最好还是忘记索引计数器,

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]])

Python 的优美( 和奇特) 特性之一是让它为您进行计算。 sum () 是内置的, 您不应该使用内置的内设名称来显示自己的标识符 。

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)

python 中的 range () 不包括最后一个元素。 换句话说, range (1, 5), is[ 1, 5) 或[ 1, 4] 。 所以, 您应该使用 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

不要将 - 1 放在范围( 列( 输入)-1) 中, 而不是使用 :

range(len(input))

区域 区域自动返回小于参数值的列表,因此不需要明确给予 -1。

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

快速回答,使用...

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

您的阵列标题是 [array]

在Python 3. 7中

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

产出产出产出产出

10

与简单的算法相比,似乎有一个普遍共识,即富油是一个复杂的解决办法。但为了找到答案:

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))

这似乎是首选解决办法:

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]]))
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

我想这就是你想做的

def sum1(arr):
sum = 0
for i in range(len(arr)):
    for j in range(len(arr[0])):
        sum += arr[i][j]
return sum

print(sum1([[1, 2], [3, 4], [5, 6]]))
curVal = sum([sum(grid[curRow + i][curCol-1:curCol+2]) for i in range(-1, 2)])




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...