需要帮助修复while循环等

时间:2019-02-10 13:58:59

标签: python while-loop

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

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(列表),则会在函数外部收到SyntaxError:'return'

3)如何获取代码以在循环中返回附加值的总和。在这种情况下,为4 + 8 + 11 + 19。

0 个答案:

没有答案
相关问题