【问题标题】:Python: Printing the sum of all items in a list via functions [duplicate]Python:通过函数打印列表中所有项目的总和[重复]
【发布时间】:2019-11-24 02:14:21
【问题描述】:

我的目标:通过函数查找并打印列表中所有项目的总和

我的代码:

def list_sum(x):
    if type(x)!='list':
        print("Invalid List item!")
    if type(x)=='list':
        list_length = len(x)
        total = 0
        i = 0
        for i in range (list_length):
            total +=x[i]
            i+=1
        print("The sum of all items in the list is: ",total)

samples = [1,3,5,6,8,45,67,89]

list_sum(samples)

我的输出:

<class 'list'>
Invalid List item!

预期: 224

为什么我得到了我得到的输出?

【问题讨论】:

  • 为什么不:sum([1,3,5,6,8,45,67,89])?
  • sum(x) 怎么样?
  • type() 不返回字符串,因此您的 type(x)!='list' 测试始终为真。
  • @SebastienD:仍然是个坏主意。
  • 接下来,for i in range(...) 将在每次循环迭代时将i 设置为一个新值。在循环中使用i+=1 完全没用。

标签: python python-3.x list


【解决方案1】:
if type(x) != list

不是

if type(x) != 'list'

【讨论】:

  • 或者你可以使用 isinstance(x, list)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 2022-08-08
  • 2018-09-04
相关资源
最近更新 更多