繁体   English   中英

在 Python 中对列表中的列表的值求和

[英]Summing The Values Of A List Inside A List In Python

我在处理这段 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)

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

[10, 26, 42]

当我尝试return sum(result)我遇到了"TypeError: 'int' object is not iterable". 同样,当我尝试创建另一个 For 循环并将 result = [] 的值相加时,我得到了相同的 TypeError 这令人困惑,因为当我创建一个简单的函数并将 sum() 应用于 return 语句时,我得到了一个总和输出没有问题。

我难住了。 有人有什么建议吗?

您已使用同名变量覆盖了函数sum 重命名变量(我称之为total ),它将按预期工作。

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))

没有什么能阻止您在内循环中使用 sum 。

def sum_lists(list_of_lists):
    result = []

    for listnumber in list_of_lists:

        result.append(sum(listnumber))

    return sum(result)

您可以使用列表理解

def sum_lists(list_of_lists):
   return sum([sum(lst) for lst in list_of_lists])

重命名变量“sum”,因为这是一个保留关键字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM