Skip to main content
 首页 » 编程设计

python之弹出索引超出范围之作业(列表,for 循环,while 循环)

2025年05月04日8lexus

<分区>

我目前正在做一道作业题:

Write and test a function modify_list that, given a list of floating point numbers as a parameter, computes the average of the values in the list and removes all values greater than the average from given list.

到目前为止,我的代码如下所示:

def modify_list(L): 
 
    average = sum(L) / (len(L)) 
    j=0 
    for J in L: 
        if J>average: 
            L.pop(J) 
        else: 
            j=j+1 
 
L=[3,12,2,21,2,1,2] 
 
modify_list(L) 
 
print(L) 

到目前为止,我已经将列表传递给函数 modify_list,然后计算列表的平均值。然后我有一个 for 循环,它获取列表中的每个值并将其与平均值进行比较。如果列表中的值大于平均值,则通过 L.pop(J) 将其删除。唯一的问题是我的错误,即:

Traceback (most recent call last): 
  File "/Users/nathan/CP/test/src/test.py", line 22, in <module> 
    modify_list(L) 
  File "/Users/nathan/CP/test/src/test.py", line 17, in modify_list 
    L.pop(J) 
IndexError: pop index out of range 

我是否应该尝试 while 循环而不是 for 循环?

我创建了一个 while 循环,它工作得很好……尽管 L.remove(i) 也工作得很好。我仍然不明白为什么 L.remove(i) 是个坏主意。 这是我的新代码:

1 def main(L):

2 平均值 = sum(L)/(len(L))

3 i=0

4 而我

5 如果 L[i]>平均:

6 L.pop(i)

7 其他:

8 i=i+1

9

10 L=[3,12,2,21,2,1,2]

11 主(左)

12 打印(L)