不使用SUM函数的嵌套列表之和(练习)

问题描述:

尝试编写一个函数,该函数获取每个列表的总和并将单个值返回到新的单个列表中。 E.g不使用SUM函数的嵌套列表之和(练习)

[[2, 7, 6], [9, 5, 1], [4, 3, 8]] 

成为

[15, 15, 15] 

我到目前为止有:

def row_sums(square): 
    total_list = [] 
    total = 0 
    for i in square: 
     for j in i: 
      total += j 
     total_list.append(total) 
    return total_list  

但这只是积累每个列表到对方造成:

[15, 30, 45] 

我不知道如何保持每个列表的总和在这里分开。 SUM函数在这里是不允许的,因为它是嵌套循环的练习。

感谢。

+2

在第一个'for'循环中设置'total = 0'。还要确保你发布了正确的缩进代码。 – Julien

您需要重置您的total计数器,然后再开始每个计数器。 另外,你不需要在外面声明它,因为你只会在里面使用它。

def row_sums(square): 
    total_list = [] 
    for i in square: 
     total = 0 
     for j in i: 
      total += j 
     total_list.append(total) 
    return total_list 
+0

为什么倒票? – levi

错误是你没有在每次循环后重新初始化变量total。取而代之的是,第一for循环初始化sum = 0里面,他就像这样:

def row_sums(square): 
    total_list = [] 
    for i in square: 
     total = 0 
     for j in i: 
      total += j 
     total_list.append(total) 
    return total_list 
+0

有道理。至少这是非常简单的事情。谢谢一堆。 –

+0

@RobertHemingway你非常欢迎。如果你喜欢我的回答,请注意。 –

+0

为什么我低调? –

您需要零时,您总为每个列表。

def row_sums(square): 
    total_list = [] 
    total = 0 
    for i in square: 
     for j in i: 
      total += j 
     total_list.append(total) 
     total = 0 
    return total_list 

只是为了好玩:

>>> list = [[2, 7, 6], [9, 5, 1], [4, 3, 8]] 
>>> import functools 
>>> [functools.reduce(lambda x, y: x + y, sublist, 0) for sublist in list] 
[15, 15, 15] 

余did't使用sum :)

你可以阅读更多关于functools.reducehere

编辑:Sevanteri在评论中指出,你也可以使用[functools.reduce(int.__add__, sublist, 0) for sublist in list] (如果你真的想驾驶你的老师疯了!)

+2

因为已经有一个整数的二进制和函数,所以你可以用int替换这个lambda函数。__add__'。 :) – Sevanteri

+0

@ Sevanteri哈哈哈我喜欢这个主意! –

+1

使用'int .__ add__'看起来有点难看,我宁愿使用'operator.add' :) – Copperfield

是不同的,扁平化的列表,并使用一台发电机(假设子表是相同的长度):

def _notsum2(lists): 
    per_yield = len(lists) 
    total = 0 
    for ind, next in enumerate(val for sublist in lists for val in sublist): 
     if ind % per_yield == 0 and ind: 
      yield total 
      total = 0 
     total += next 
    yield total 


if __name__ == '__main__': 
    li = [[2, 7, 6], [9, 5, 1], [4, 3, 8]] 
    print [g for g in _notsum2(li)] 

你也可以做到这一点使用map和列表理解为:

l=[[2, 7, 6], [9, 5, 1], [4, 3, 8]] 
a,b,c=[x for x in l] 
map(lambda x,y,z:x+y+z, a,b,c) 

[sum(i) for i in zip(*[[2, 7, 6], [9, 5, 1], [4, 3, 8]])]

bultin zip func正是你需要的东西

+1

OP希望不用'sum'来完成它,也希望每个子列表中元素的总和不是与所有子列表的组合 – Copperfield