错误提示
在执行 Python3 程序时,错误提示 TypeError: slice indices must be integers or None or have an __index__ method
,小编的报错代码片段位置如下:
if model == 'autocovariance':
u = signal.detrend(u, type='linear')
N = np.size(u)
tmax = dt * N
norm_num = np.linalg.norm(u)**2
dummy = np.correlate(u, u, "full")/norm_num
lags = signal.correlation_lags(len(u), len(u), mode="full")
R = dummy[N-1:]
tLag = lags[N-1:]*dt
ind = np.where(np.diff(R > 0)==True)[0]+1
if np.size(ind) >= 1:
ind = ind[0]
else:
L = np.nan
if method == 1:
T = np.trapz(R[:ind], tLag[:ind])
L = T * meanU
elif method == 2:
indThres = np.where(abs(tLag-tmax) == min(abs(tLag-tmax)))
indThres = min(indThres, ind)
x = tLag[:indThres]
y = R[:indThres]
提示的出错代码行为:
x = tLag[:indThres]
错误原因
出错原因:除号使用/,改成//就好,
在Python2.x中,使用 /,整数相除为整数,会把小数部分忽略,浮点数相除会保留小数部分
在Python3.x中,使用 /,整数与浮点数相除都是浮点数
使用 //,在Python2.x、Python3.x中都一样,取整除法,会忽略小数部分,向下取整
print(5/3)
print(5//3)
1.6666666666666667
1
解决方案
方法一 将变量 i 强制 int 即可解决
# 原代码
for i in part:
x = spike[i:i+scale, :]
# 修改为
for i in part:
x = spike[int(i): int(i+scale), :]
将出错代码行修改为:
x = tLag[: int(indThres)]