python - 为什么会出现int类型错误?类型错误

标签 python numpy scipy

我收到一个错误, 类型错误:切片索引必须是整数或 None 或具有 index 方法。 回溯就像

Traceback (most recent call last):
  File "test.py", line 24, in <module>
    wavdata = wav[z:q]
TypeError: slice indices must be integers or None or have an __index__ method

我的代码是

#coding:utf-8
import wave
import numpy as np
from pylab import *

def wavread(filename):
    wf = wave.open(filename, "r")
    fs = wf.getframerate()
    x = wf.readframes(wf.getnframes())
    x = np.frombuffer(x, dtype="int16") / 32768.0  # (-1, 1)に正規化
    wf.close()
    return x, float(fs)

if __name__ == "__main__":
    wav, fs = wavread("3_7_9.wav")
    t = np.arange(0.0, len(wav) / fs, 1/fs)

    center = len(wav) // 2  
    cuttime = 0.04         
    z = center-cuttime // 2*fs
    q= center + cuttime // 2*fs
    wavdata = wav[z:q]
    time = t[z:q]

    plot(time * 1000, wavdata)
    xlabel("time [ms]")
    ylabel("amplitude")
    savefig("waveform.png")
    show()

我认为center & z & q 变量是int类型,所以我真的不明白为什么会发生这个错误。首先,我写了这一部分

if __name__ == "__main__":
    wav, fs = wavread("3_7_9.wav")
    t = np.arange(0.0, len(wav) / fs, 1/fs)

    center = len(wav) / 2  
    cuttime = 0.04         
    z = center-cuttime / 2*fs
    q= center + cuttime / 2*fs
    wavdata = wav[z:q]
    time = t[z:q]

    plot(time * 1000, wavdata)
    xlabel("time [ms]")
    ylabel("amplitude")
    savefig("waveform.png")
    show()

所以这些除法部分不是int类型而是float类型,因此我可以理解为什么会发生这个错误。但是现在我将这些部分更改为//,所以这些部分是int。那么,我该如何修复这个错误?

最佳答案

变量zq仍然是float

center = len(wav) // 2  
cuttime = 0.04         
z = center - cuttime // 2 * fs
q = center + cuttime // 2 * fs

因为cuttimefs都是float,所以整个表达式变成float

您需要将其转换为int,例如

z = int(center - cuttime // 2 * fs)
q = int(center + cuttime // 2 * fs)

关于python - 为什么会出现int类型错误?类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083168/

相关文章:

python - 二维 numpy 数组的边界框

python - 无法在 python 3.9 版中安装 numpy

python - 实现对数正态拟合的 KS 检验

python - python 的哪个统计模块支持单向方差分析和事后测试(Tukey、Scheffe 或其他)?

python - 具有不同特征维度的FeatureUnion

python - 销毁子解释器后释放 GIL

javascript - Python Flask Cors 问题

python - 我可以修改漂亮的 soup 标签中的文本而不将其转换为字符串吗?

python - 如何在Python的进程之间共享一个非常大的字典

python - 提高 python dblquad 和多处理的速度