How to nicely handle [:-0] slicing?

2019-02-26 21:21发布

问题:

In implementing an autocorrelation function I have a term like

for k in range(start,N):
    c[k] = np.sum(f[:-k] * f[k:])/(N-k)

Now everything works fine if start = 1 but I'd like to handle nicely the start at 0 case without a conditional.

Obviously it doesn't work as it is because f[:-0] == f[:0] and returns an empty array, while I'd want the full array in that case.

回答1:

Don't use negative indices in this case

f[:len(f)-k]

For k == 0 it returns the whole array. For any other positive k it's equivalent to f[:-k]



回答2:

If k is zero use None for the slice, like so:

for k in range(start,N):
    c[k] = np.sum(f[:-k if k else None] * f[k:])/(N-k)


回答3:

There are several ways of doing it, by testing if k==0 before applying the formula. It's up to you to find the only that looks nicer.

for k in range(start,N):
    c[k] = np.sum(f[:-k] * f[k:])/(N-k) if k != 0 else np.sum(f * f[k:])/(N-k)

for k in range(start,N):
    end_in_list = -k if k != 0 else None
    start_in_list = k
    c[k] = np.sum(f[:end_in_list] * f[start_in_list:])/(N-k)