将Python中列表中的列表值求和

问题描述 投票:0回答:1

我在这段Python代码中遇到了一些麻烦。挑战如下:

“编写一个名为sum_lists的函数。sum_lists应该采用一个参数,它将是整数列表的列表。 sum_lists应该返回每个列表中每个数字相加的总和。

下面是一些将测试您的功能的代码行。您可以更改变量的值以测试您的功能不同的输入。

如果您的功能正常工作,最初将打印:78“

list_of_lists = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
print(sum_lists(list_of_lists))

这是到目前为止我整理的代码。就这样,我得到这样的输出:

def sum_lists(list_of_lists):
    result = []

    #extract what list from the bigger list
    for listnumber in list_of_lists:
        sum = 0

        #add the value of the smaller list
        for value in listnumber:
            sum += value
        result.append(sum)

        #add the result values together
        #for resultvalue in result:
        #    result += resultvalue

    return sum(result)

每个列表的值相加在一起,但结果= []部分中仍然是3个单独的值:

[10, 26, 42]

[当我尝试return sum(result)时,我被"TypeError: 'int' object is not iterable".击中。同样,当我尝试制作另一个For循环并将结果= []的值加在一起时,我得到相同的TypeError,这是令人困惑的,因为当我做一个简单的函数并将sum()应用于return语句,我得到的输出没有问题。

我很困惑。任何人有任何建议吗?

python nested-lists
1个回答
0
投票

您已经用变量覆盖了函数sum。重命名它就可以了。

list_of_lists = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

def sum_lists(list_of_lists):
    result = []

    #extract what list from the bigger list
    for listnumber in list_of_lists:
        total = 0

        #add the value of the smaller list
        for value in listnumber:
            total += value
        result.append(total)

        #add the result values together
        #for resultvalue in result:
        #    result += resultvalue

    return sum(result)

print(sum_lists(list_of_lists))
© www.soinside.com 2019 - 2024. All rights reserved.