Python 为什么我得到“TypeError:'int'对象不可编辑”

Python 为什么我得到“TypeError:'int'对象不可编辑”,python,iterable,Python,Iterable,我得到TypeError:运行此代码时,“int”对象不可编辑,怎么了 # Write a function called nested_sum that # takes a nested list of integers and add up # the elements from all of the nested lists. def nested_sum(lista): total = 0 for item in lista: item = sum(ite

我得到TypeError:运行此代码时,“int”对象不可编辑,怎么了

# Write a function called nested_sum that
# takes a nested list of integers and add up
# the elements from all of the nested lists.

def nested_sum(lista):
    total = 0
    for item in lista:
       item = sum(item)
       total = total + item
    return total
list1 = [ 1 , 2  ,3 , [7, 3] ]
nested_sum(list1)
函数sum以迭代器作为参数。在代码的第8行中,使用了带int的sum。list1数组包含数字和数组。
您可以找到有关sum函数的信息

sum将列表作为其参数

您可以将问题行更改为:

item = sum(item) if isinstance(item, list) else item

你也可以让你自己的函数递归,因为你必须自己做一个求和函数。为什么要在编写函数时使用另一个函数来执行完全相同的操作

def nested_sum(lista):
total = 0
for item in lista:
   if isinstance(item, list) or isinstance(item, tuple):
      item = nested_sum(item)
   total = total + item
return total
你不能把这个加起来:

l = [1,2,3,[4,5]]
sum(1)
解决方案:

def nested_sum(ls):
    total = 0
    for e in ls:
       if not isinstance(e, int):
           items = sum(e)
           total += items
       else:
           items = e
           total += items
    return total
问题陈述

编写一个名为nested_sum的函数,该函数接受一个嵌套的整数列表,并将所有嵌套列表中的元素相加

行动尝试

答复

您在解决这个问题上做了很好的尝试,但是您得到了TypeError,因为您正在使用一个参数调用sum函数,而sum函数不是设计用来调用的

我鼓励您阅读有关sum函数的Python。但是,我也会给你一点解释

sum函数最多接受两个参数。第一个参数必须是可编辑的对象。iterable对象的一些示例是列表、dict和集合。如果它是某种集合,那么它可能是一个安全的假设,即它是可编辑的。sum函数的第二个参数是可选的。这是一个数字,表示您将开始添加到的第一个数字。如果省略第二个参数,则将开始向0添加。第二个参数与函数无关,因此在本例中可以忽略它

考虑到这一点,您现在应该能够理解为什么以int作为第一个参数调用sum函数会导致Python解释器抛出错误

def nested_sum(lista):
    total = 0
    for item in lista:
       item = sum(item) # The error is here
       total = total + item
    return total
list1 = [ 1 , 2  ,3 , [7, 3] ]
nested_sum(list1)
您可以使用@JacobIRR的答案来修复错误,即将问题行替换为:

item=sumitem如果是InstanceItem,则列出else项

然而,这一行可能会让一些人感到困惑,因此我将冒昧地让它变得更加明显

def nested_sum(lista):
    total = 0
    for item in lista:
       if isinstance(item, list): # if the item is a list
           item = sum(item)       # sum the list
       total += item              # total = total + item
    return total
list1 = [ 1 , 2  ,3 , [7, 3] ]
nested_sum(list1)
另外,虽然这段代码可能适用于您提供的示例列表。考虑一下如果调用一个嵌套更进一步的函数,将会发生什么。 清单1=[1,2,3,4,5,6,7]]


我希望这不仅能帮助您解决问题,还能理解求和函数的用法。

因为您在做sum1。我认为sum1应该给出1,这有什么错?thanksreturn sum[nested_sumx if is instancex,list else x for x in lista]我不知道为什么会被否决。我已经运行了代码,它运行得很好。也不知道为什么这条线索中的所有其他答案都被否决了。它们似乎都很合理。
def nested_sum(lista):
    total = 0
    for item in lista:
       if isinstance(item, list): # if the item is a list
           item = sum(item)       # sum the list
       total += item              # total = total + item
    return total
list1 = [ 1 , 2  ,3 , [7, 3] ]
nested_sum(list1)