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

时间:2015-05-09 10:52:05

标签: 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")

3 个答案:

答案 0 :(得分:1)

注意一件事:

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

答案 1 :(得分:-1)

index2是一个int,因此无需将其转换为indexy。 Python中的Indizes从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))

答案 2 :(得分:-1)

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

counter应该不通过int遍历列表,甚至你指的是一个超出列表索引范围的值:

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

2 - 您无法迭代int的固定值。

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

for counter in score

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

您的代码需要进行优化。