Python 我无法让我的代码工作。它一直在说:索引器:列表索引超出范围

Python 我无法让我的代码工作。它一直在说:索引器:列表索引超出范围,python,Python,我的代码是使用列表的长度来尝试查找超过输入数字的分数百分比。这一切都是有意义的,但我认为一些代码需要编辑,因为它会产生错误代码。我如何修复它??? 代码如下: result = [("bob",7),("jeff",2),("harold",3)] score = [7,2,3] lower = [] higher = [] index2 = len(score) indexy = int(index2) index1 = 0 chosen = int(input("the number of

我的代码是使用列表的长度来尝试查找超过输入数字的分数百分比。这一切都是有意义的,但我认为一些代码需要编辑,因为它会产生错误代码。我如何修复它??? 代码如下:

result = [("bob",7),("jeff",2),("harold",3)]
score = [7,2,3]
lower = []
higher = []
index2 = len(score)
indexy = int(index2)
index1 = 0
chosen = int(input("the number of marks you want the percentage to be displayed higher than:"))
for counter in score[indexy]:
    if score[index1] >= chosen:
        higher.append(score[index1])
    else:
        lower.append(score[index1])
    index1 = index1 + 1


original = indexy
new = len(higher)
decrease = int(original) - int(new)
finished1 = decrease/original
finished = finished1 * 100
finishedlow = original - finished
print(finished,"% of the students got over",chosen,"marks")
print(finishedlow,"% of the students got under",chosen,"marks")

index2
是一个int,因此无需将其转换为
indexy
。Python中的索引从0开始计数,因此最高的索引是
len(list)-1
。 您有一个
计数器
,那么为什么在for循环中使用
index1
?您不能迭代数字
分数[indexy]

results = [("bob",7),("jeff",2),("harold",3)]

chosen = int(input("the number of marks you want the percentage to be displayed higher than:"))
higher = sum(score >= chosen for name, score in results)

finished = higher / len(results)
finishedlow = 1 - finished
print("{0:.0%} of the students got over {1} marks".format(finished, chosen))
print("{0:.0%} of the students got under {1} marks".format(finishedlow, chosen))
请注意一件事:

>>>score = [7,2,3]
>>>len(score) = 3
但是,列表的索引从0开始计数,所以

>>>score[3]
IndexError: list index out of range
将第12行修改为:

...
for counter in score:
    if counter >= chosen:
        ...
如果您确实想获取索引并使用它们:

....
for index, number in enumerate(score):
    if score[index] >= chosen:
        ......

您的错误在第9行:
对于分数[indexy]中的计数器:

计数器
应该遍历列表,而不是通过
int
迭代,即使您引用的值超出了列表的索引范围:

1-记住索引应该是从0到(len(list)-0)

2-不能迭代int的固定值

因此,您应该将第9行更改为:

用于分数中的计数器

但我不确定您将从代码中得到什么结果,您需要检查您的代码逻辑


您的代码中有很多需要优化的地方。

如果您可以发布错误并进行回溯,我们就不需要运行它了。在哪一行中索引错误?你为什么要保守秘密?