总结一个列表列表来获得总结列表Python [英] Sum a list of lists to get a sum list Python

查看:99
本文介绍了总结一个列表列表来获得总结列表Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个定义一个帮助函数,它列出一个列表以获得一个和列表。

I'm trying to create a define a helper function that sums a list of lists to get a sum list.

例如:

For example:

[[1,2,3],[1,2,3],[2,3,4]]

[4,7,10]

我在另一篇文章中发现了这一点:

I found this on another post to work:

[sum(i) for i in zip(*listoflists)]

我需要将它转换成一个已定义的函数。这是我到目前为止,但它不起作用。

I need to to translate this into a defined function. This is what I have so far but it's not working.

def addhours(listoflists):
    for list in zip(*listoflists):
        newsum = sum (list)
return newsum


推荐答案

由于该函数非常小,您还可以使用匿名定义:

Since the function is quite small, you could also use an anonymous definition:

>>> addhours = lambda l: [sum(i) for i in zip(*l)]
>>> addhours([[1,2,3],[1,2,3],[2,3,4]])
>>> [4,7,10]

这篇关于总结一个列表列表来获得总结列表Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆