简体   繁体   English

Python3列表索引错误

[英]Python3 list index Error

Recently, I have started learning Python. 最近,我开始学习Python。 I'd like to make a cosine distribution simulation. 我想进行余弦分布模拟。 "Index Error:list index out of range" is shown on my display. 我的显示器上显示“索引错误:列表索引超出范围”。 but I think I define a length of list, and I write 0 < key < len(thickness). 但我认为我定义了列表的长度,并写了0 <key <len(thickness)。 why the Error is shown on my display?? 为什么我的显示器上显示错误?

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()

It should be if 0 <= key < len(thickness): . 应该是if 0 <= key < len(thickness): This is because array indices go from 0 to len(thickness)-1 , not 1 to len(thickness) . 这是因为数组索引从0len(thickness)-1 ,而不是1len(thickness)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM