python:for循环紧凑表示

时间:2012-12-30 03:34:24

标签: python numpy

Python,Numpy

是否有更紧凑的方式对数组元素进行操作,而不必使用标准for循环。?

例如,请考虑以下功能:

filterData(A):
    B = numpy.zeros(len(A));
    B[0] = (A[0] + A[1])/2.0;
    for i in range(1, len(A)): 
        B[i] = (A[i]-A[i-1])/2.0;
    return B;

2 个答案:

答案 0 :(得分:5)

Numpy有一个diff operator,适用于numpy数组和Python本机数组。您可以将代码重写为:

def filterData(A):
    B = numpy.zeros(len(A));
    B[1:] = np.diff( A )/2.0
    B[0] = (A[0] + A[1])/2.0;
    return B

答案 1 :(得分:1)

还有numpy.ediff1d,它允许您使用to_endto_begin参数明确地前置或附加到差异,例如:

>>> import numpy as np
>>> a = np.arange(10.)
>>> diff = np.ediff1d(a,to_begin = a[:2].sum()) / 2.
>>> diff
array([ 0.5,  0.5,  0.5,  0.5,  0.5,  0.5,  0.5,  0.5,  0.5,  0.5])
>>> diff.size
10