### 改變數組中的元素——Python

#### [英]Changing elements in an Array - Python

``````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`.

s是一個向量包含很多元素我希望([s0,s1,s2,....、sn-2 sn-1]),然后我打算創建一個數組(初始的零)同樣大小的年代。

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.

## 2 个解决方案

### #1

1

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]]`.

zip將它們成對地組合在一起，比如[[s0, s1]， [s1, s2]，…[sn-2 sn-1]]。

Then you just divide the second element of each sublist by the first.

### #2

1

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