How to nicely handle [:-0] slicing?

a 夏天 提交于 2020-01-11 10:48:07

问题


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)


来源:https://stackoverflow.com/questions/35264670/how-to-nicely-handle-0-slicing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!