如何用一个列表求整数和?TypeError:不支持+:“int”和“list”的操作数类型

2024-10-04 05:34:13 发布

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

首先,我是python的新生,所以这可能很容易,但在这里询问之前,我尽了最大努力进行了研究。不管怎样,如果我把“在minListe中为高”改为“在[5,2,-4,2,-1,0,2,-2,3,0,7]中为minListe”,这是可行的,但这还不够好。。。有人知道如何做到这一点,而不必在函数中包含我的列表吗?你知道吗

total = 0

tall = 0

minListe = [5, 2, -4, 2, -1, 0, 2, -2, 3, 0, 7]

def funksjon2(total):

    total = 0 
    for tall in minListe:
        if minListe == 0:
            break
        total = total + minListe
    return (total)

def main():

    print(funksjon2(total))


if __name__ == "__main__":
    main(

)

Tags: 函数in列表forreturnifmaindef
3条回答

您试图将一个列表添加到int中,所以直观地说这是行不通的。您的错误如下:

if minListe == 0:
    total = total + minListe

相反,这应该是

if tall == 0:
    total = total + tall
    # or 'total += tall'

因为tallminListe中的int,而asminListe是列表本身。你知道吗

解决方案是: 总计=0 对于minListe中的tall: 如果minListe==0: 打破 合计=合计+高 回报(总计)

您不应该添加带有int的列表。只需将高迭代器添加到总数中即可。你知道吗

如果我正确理解了你的逻辑,那么你就是在尝试做以下事情。请尝试下面的代码,如果有效或无效,请在下面添加注释。我已经添加了一些评论,我已经修改了东西

minListe = [5, 2, -4, 2, -1, 0, 2, -2, 3, 0, 7]

def funksjon2(minListe):
    total = 0
    for tall in minListe:
        if tall == 0: # Replaced minListe by tall
            break
        total = total + tall # # Replaced minListe by tall
    return (total)

print(funksjon2(minListe))

> 4 # Answer

相关问题 更多 >