python对列表列表的值求和 [英] python sum the values of lists of list

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

问题描述

我有一个列表列表,我需要对内部列表求和,例如,

I have list of lists and i need to sum the inner lists, for example,

a = [[1,2,3], [2,1,4], [4,3,6]]

对于我来说,a [i]的len是相同的,也就是说所有内部列表的维数都相同.

for my case, the len of a[i] is same, that is all the inner lists have same dimension.

我需要输出为

result = [6,7,13]

我所做的是:

result = [sum(a[i]) for i in range(len(a))]

由于我的len(a)非常高,所以我希望有一种不使用for循环即可获得结果的替代方法.

Since my len(a) is very high, i hope there will be a alternative way to get the result without using the for loop.

推荐答案

result = map(sum, a)

这就是我会做的方式.或者:

Is the way I would do it. Alternatively:

result = [sum(b) for b in a]

第二个变体与您的变体相同,只是它避免了不必要的range语句.在Python中,您可以直接遍历列表,而不必保留单独的变量作为索引.

The second variation is the same as yours, except it avoids the unnecessary range statement. In Python, you can iterate over lists directly without having to keep a separate variable as an index.

这篇关于python对列表列表的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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