我不能让我的代码工作。它一直在说:IndexError:List索引超出范围

2024-04-18 08:57:43 发布

您现在位置: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 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")

Tags: ofthe代码lenlowerintscorechosen
3条回答

index2是一个int,因此无需将其转换为indexy。Python中的索引是从0开始计数的,因此最高的索引是len(list)-1。 你有一个counter,那么为什么在for循环中使用index1?不能对数字score[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))

你的错误在第9行:for counter in score[indexy]:

counter应该遍历列表,而不是遍历int,即使您引用的值超出了列表的索引范围:

1-记住索引应该从0到(len(list)-0)。你知道吗

2-不能遍历int的固定值

所以,您应该将第9行改为:

for counter in score

但是我不确定你从代码中得到的结果,你需要检查你的代码逻辑。你知道吗

在你的代码中有很多需要优化的地方。你知道吗

注意一件事:

>>>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:
        ......

相关问题 更多 >