在python中使用numpy轻松添加两个数组? [英] Simple adding two arrays using numpy in python?
问题描述
这可能是一个简单的问题.但是,我想澄清以下代码的工作原理.
This might be a simple question. However, I wanted to get some clarifications of how the following code works.
a = np.arange(8)
a
array([1,2,3,4,5,6,7])
Example Function = a[0:-1]+a[1:]/2.0
在示例函数中,我想引起您注意数组a[0:-1]+a[1:]
之间的加号.这是如何运作的?看起来像什么?
In the Example Function, I want to draw your attention to the plus sign between the array a[0:-1]+a[1:]
. How does that work? What does that look like?
例如,加号(加法)是否添加了每个数组的第一个索引? (例如1+2
)还是将所有内容加在一起? (例如1+2+2+3+3+4+4+5+5+6+6+7
)
For instance, is the plus sign (addition) adding the first index of each array? (e.g 1+2
) or add everything together? (e.g 1+2+2+3+3+4+4+5+5+6+6+7
)
然后,我认为/2.0
只是将其除以2
...
Then, I assume /2.0
is just dividing it by 2
...
推荐答案
一个numpy数组使用矢量代数,因为您只能在两个数组具有相同的维数时才添加两个数组
A numpy array uses vector algebra in that you can only add two arrays if they have the same dimensions as you are adding element by element
a = [1,2,3,4,5]
b = [1,1,1]
a+b # will throw an error
白痴
a = [1,2,3,4,5]
b = [1,1,1,1,1]
a+b # is ok
该划分也是逐元素进行的.
The division is also element by element.
现在您有关索引的问题
a = [1,2,3,4,5]
a[0:-1]= [1,2,3,4]
a[1:] = [2,3,4,5]
或更普遍地a[index_start: index_end]
在start_index
处是包含性的,但在end_index
中是排他性的-除非为您提供a[start_index:]
,其中包括直到最后一个元素的所有内容.
or more generally a[index_start: index_end]
is inclusive at the start_index
but exclusive at the end_index
- unless you are given a a[start_index:]
where it includes everything up to and including the last element.
我的最后一个提示是尝试使用这些结构-尝试不同的东西没有任何危害,计算机不会在此处或此处以错误的值爆炸.当然,除非您尝试这样做.
My final tip is just to try and play around with the structures - there is no harm in trying different things, the computer will not explode with a wrong value here or there. Unless you trying to do so of course.
这篇关于在python中使用numpy轻松添加两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!