[英]Python3 list index Error
最近,我开始学习Python。 我想进行余弦分布模拟。 我的显示器上显示“索引错误:列表索引超出范围”。 但我认为我定义了列表的长度,并写了0 <key <len(thickness)。 为什么我的显示器上显示错误?
import math
def main():
height = 20
thickness = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
with open('output/output.csv', 'w', encoding = 'utf-8' ) as f:
f.write('x,thikcness\n')
for t in range(90):
deg = t
rad = math.radians(deg)
x = height * math.tan(rad)
key = round(x)
if 0 < key <= len(thickness):
thickness[key] += 1
for t in len(thickness):
f.write(str(thickness[t]) + '\n')
if __name__ == "__main__":
main()
应该是if 0 <= key < len(thickness):
这是因为数组索引从0
到len(thickness)-1
,而不是1
到len(thickness)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.