python - 索引错误 : list index out of range - cannot reason the logic

标签 python numpy indexing

我之前询问过这段代码并得到了一些有用的答案,但我想再添加一个步骤,这给了我一个错误。该代码生成一组余弦波,然后将它们全部相加。 这是代码:

from pylab import *
from numpy import *
freq=[]
x=linspace(-4000,4000,8001)
sum=0
for i in range(1,121,1):
    freq.append(cos(2*pi*i*(x/8001)))
    sum=(sum + freq[i])/i

plot(x,sum)
show()

使用这段代码,我得到错误“第 8 行,在 总和=(总和+频率[i])/i IndexError: 列表索引超出范围"

但是,当我从零开始范围时:for i in range(121) 并删除 sum=sum + freq[i] 的分母中的 i程序运行良好。

我不明白当列表中没有零时它如何看到索引超出范围而当有零时它工作?

最佳答案

当您从 i=1 开始迭代时:

freq.append(cos(2*pi*i*(x/8001)))
sum=(sum + freq[1])/i   => freq[1] (index out of range)

希望对您有所帮助。

关于python - 索引错误 : list index out of range - cannot reason the logic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622541/

相关文章:

python - python 导入顺序如何影响名称?

python - Tensorboard:无标量值

python - python 中的 4d 插值

python - 读取数据到 numpy 数组

ajax - 针对 ajax 调用的 Google 搜索优化

当where条件有if子句时MySQL不使用索引

Python:dataframe的索引是三列的组合,如何将它们分开?

python - 在 python 中输入 Callable 到特定方法

python - matplotlib show() 方法不打开窗口

python - 最近的邻居