def q(s):
n = len(s)
v = numpy.zeros(n, dtype=float)
s is a vector containing however many elements I wish ([s0,s1,s2,....,sn-2,sn-1]) , and I intend to then create an array (initial full of zeros) that is of the same size as s.
My aim is to then to change the zero elements in this array to [s1/s0 , s2/s1 , s3/s2..., sn-1/sn-2].
I understand that a for loop is required, but I am finding it difficult to program this. Could anybody offer a hand? Thank you.
-
Please try something first, then if you're stuck tell us what you tried and where you got stuck and the Python community here at Stack Overflow would love to help.Bleeding Fingers– Bleeding Fingers2014年02月08日 18:04:09 +00:00Commented Feb 8, 2014 at 18:04
2 Answers 2
You don't need to create an array of zeros first.
[b / a for a, b in zip(s, s[1:])]
Explanation
s your list, s[1:] is you list except for the first element.
zip puts them together in pairs, like [[s0, s1], [s1, s2],... [sn-2, sn-1]].
Then you just divide the second element of each sublist by the first.
2 Comments
You don't need an explicit loop if you're using a NumPy array:
>>> import numpy as np
>>> a = np.array([10, 20, 30, 40, 50], dtype=float)
>>> a[1:]/a[:-1]
array([ 2. , 1.5 , 1.33333333, 1.25 ])