需要帮助修复while循环和

2024-04-19 18:04:41 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码返回以下内容:

list = [1, 3, 4, 5, 6]

while len(list) >= 0:
    smallest_no = sorted(list)[0]
    second_smallest_no = sorted(list)[1]
    sum_smallest_nos = smallest_no + second_smallest_no

    list.remove(smallest_no)
    list.remove(second_smallest_no)
    list.append(sum_smallest_nos)

    print(list)

输出:

[4, 5, 6, 4]
[5, 6, 8]
[8, 11]
[19]

错误:

IndexError                                Traceback (most recent call last)
<ipython-input-7-d6ccc5cb5f76> in <module>()
      5 while len(list) >= 0:
      6     smallest_no = sorted(list)[0]
----> 7     second_smallest_no = sorted(list)[1]
      8     sum_smallest_nos = smallest_no + second_smallest_no
      9 
IndexError: list index out of range

1)为什么会发生这种情况,我如何解决?你知道吗

2)如果我把它改为return(list),我得到SyntaxError:'return'在函数外部

3)如何让代码返回循环中附加值的总和。在这种情况下,4+8+11+19。你知道吗


Tags: no代码lenreturn情况removelistsum