[英]calculate the mid points of a vector using Python
I started to learn python from scratch. 我开始从零开始学习python。 I got some issues while doing the following problem.
执行以下问题时遇到一些问题。
I have the following vector , x_vector = (0,1,2,3,4,5,6,7,8,9)
. 我有以下向量
x_vector = (0,1,2,3,4,5,6,7,8,9)
。 Using this vector, I need to create this new vector x1 = (-0.5,0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5)
. 使用这个向量,我需要创建这个新向量
x1 = (-0.5,0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5)
。
Basically the desired vector should have first element -0.5, mid points between each elements and the last element +0.5. 基本上,所需向量应具有第一个元素-0.5,每个元素之间的中点和最后一个元素+0.5。
The code I tried so far as follows: 我到目前为止尝试的代码如下:
import numpy as np
x_vector=np.array([0,1,2,3,4,5,6,7,8,9])
x=len(x_vector)
mid=np.zeros(x+1)
for i in range (0,x):
if i==0 :
mid[i]= x_vector[i]-0.5
else :
mid[i]=(x_vector[i] + x_vector[i+1])/2
i +=1
Seems like this doesn't give the desired output. 似乎这样无法提供所需的输出。 Can you one help me to figure out what can I do to get correct output?
您能帮我弄清楚我该怎么做才能获得正确的输出吗?
Using itertools.pairwise
: 使用
itertools.pairwise
:
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
res = []
res.append(min(x_vector)-0.5)
res.append(max(x_vector)+0.5)
res.extend([np.mean(z) for z in pairwise(x_vector)])
sorted(res)
Output: 输出:
[-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
Consider, what will happen for i = 0
and i = 1
in your loop: 考虑一下,对于
i = 0
和i = 1
在循环中会发生什么:
mid[0] = x_vector[0] - 0.5 # = -0.5
mid[1] = (x_vector[1] + x_vector[2]) / 2 # (1 + 2) / 2 = 3 / 2 = 1 (or 1.5 if python3)
you mismatched indexes. 您索引不匹配。 Try this:
尝试这个:
for i in range (0,x):
if i == 0:
mid[i] = x_vector[i]-0.5
else :
mid[i] = (x_vector[i - 1] + x_vector[i]) / 2.0
Note, that i changed division to divide by 2.0
instead of 2
- this will make sure, that division result will be double (number with fraction) instead of integer (number without fraction, in python 2 division two integers will round to integer). 注意,我将除法更改为除以
2.0
而不是2
这将确保除法结果将是double(带分数的数字)而不是整数(在Python 2除法中,两个整数将四舍五入为整数)。 Also i += 1
is redundant, i
variable in for loop
will updated (overwriting your += 1
statement) every loop iteration. 同样,
i += 1
是冗余的, for loop
i
变量将在每次循环迭代时更新(覆盖+= 1
语句)。
It is not clear whether this is a homework, but given that you are using numpy
I think it is fair game to use it as its whole potential, in this case you can just do: 目前尚不清楚这是否是一项家庭作业,但是鉴于您使用的是
numpy
我认为将其作为全部功能来使用是公平的,在这种情况下,您可以执行以下操作:
import numpy as np
x_vector=np.array([0,1,2,3,4,5,6,7,8,9])
a = np.insert(x, 0, x[0] - 1)
b = np.append(x, x[-1] + 1)
mid = (a + b) / 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.