改變數組中的元素——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].

我的目標是將這個數組中的零元素更改為[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.

我知道需要一個for循環,但是我發現很難對它進行編程。有人能幫忙嗎?謝謝你!

2 个解决方案

#1


1  

You don't need to create an array of zeros first.

您不需要首先創建一個0數組。

[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:

如果使用NumPy數組,則不需要顯式循環:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/02/08/72f99c58fcb2c88f2a196b480ad4ac9.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com