Python 不使用求和函数的嵌套列表的求和(练习)
尝试编写一个函数,获取每个列表的总和,并在新的单个列表中返回单个值。 例如 变成Python 不使用求和函数的嵌套列表的求和(练习),python,python-3.x,Python,Python 3.x,尝试编写一个函数,获取每个列表的总和,并在新的单个列表中返回单个值。 例如 变成 [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, 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函数,因为它是嵌套循环的练习
谢谢。您需要先重置您的
总数
计数器,然后再启动每个inside for。
另外,您不需要在外部声明它,因为您将只在内部使用它
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
错误在于每次循环后都没有重新初始化
total
变量。相反,在he中初始化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
您需要将每个列表的总数归零
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]
我没有使用sum
:)
您可以阅读有关functools.reduce的更多信息
编辑:正如Sevanteri在评论中指出的那样,您也可以使用[functools.reduce(int.\uuuuu add\uuuu,sublist,0)作为列表中的子列表]
(如果你真的想让你的老师发疯!)要与众不同,请将列表展平并使用生成器(假设子列表长度相同):
您也可以使用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)
[邮政编码中i的总和(*[2,7,6],[9,5,1],[4,3,8])]
bultin zip func是您在第一个for
循环中所需要的设置total=0
。还要确保您发布了正确缩进的代码。至少这件事很简单。非常感谢。@RobertHemingway,非常欢迎你。如果你喜欢我的答案,请投票表决。既然已经有一个整数的二进制和函数,你可以用int替换lambda@Sevanteri哈哈哈我喜欢这个主意!使用int.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
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)]
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)