【问题标题】:Python sum of list not adding the first and last列表的Python总和不添加第一个和最后一个
【发布时间】:2018-07-14 15:16:52
【问题描述】:
def sumfirstlast(num):
new_list = list(num)
for sum in new_list:
    total = int(new_list.pop(0)) + int(new_list.pop())
return(total)


number = input("Input number")
display = sumfirstlast(number)
print(display)

为什么当我输入 43682 时它返回 11 而不是 6 ?由于我在列表中添加了第一个和最后一个数字

【问题讨论】:

  • 你需要将你的字符串转换为整数,现在你正在做字符串连接
  • oml 简单的东西!谢谢完全错过了!
  • 使用sum 作为变量名是不好的做法,因为已经有一个名为sum() 的内置函数。 docs.python.org/3/library/functions.html#sum(这不是这个特定错误的原因,但这是一个常见的初学者错误,很容易导致难以理解的错误)
  • 你的问题是你已经在for 循环中得到它 - 你将第一个和最后一个元素添加在一起并将它们从列表中删除,然后再做一次。因此,不是将 4 和 2 相加,而是将 3 和 8 相加。

标签: python


【解决方案1】:

我相信total = int(new_list[0])) + int(new_list[len(new_list) - 1]) 应该可以工作。

【讨论】:

  • 您好,这行得通!但是我能问一下这段代码是什么意思吗? int(new_list[len(new_list) - 1]) 抱歉,我对 python 还很陌生,而且我很难使用 list :(
  • new_list[-1] 是获取列表最后一个元素的更好方法。
  • @RobWatts 请问为什么 new_list.pop() 在这种情况下不起作用?
  • new_list.pop() 会起作用,但会在此过程中修改new_list,这并不是真正必要的,并且可能会使事情变得混乱
  • @RobWatts 我看到了变化,但基本上不想复制你的答案
【解决方案2】:

问题是不必要的for循环,结合修改列表:

for sum in new_list:
    total = int(new_list.pop(0)) + int(new_list.pop())

如果 new_list['4', '3', '6', '8', '2'],则在第一次迭代中,总数正确设置为 6。但是,您仍在循环中 - 将再次设置总数,这次将 3 和 8 相加。

所以你的方法应该只是将第一个和最后一个元素添加在一起,没有任何循环:

total = int(new_list[0]) + int(new_list[-1])

大多数时候,您应该使用索引从列表中获取项目,而不是使用pop()pop 主要用于从列表中删除项目;它只是为了方便返回删除的项目。

【讨论】:

    猜你喜欢
    • 2011-12-11
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2021-10-12
    • 2020-11-22
    • 1970-01-01
    • 2010-09-24
    • 2012-02-02
    相关资源
    最近更新 更多