如何对列表的相同索引求和? [英] How to sum over same indices of list of lists?

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

问题描述

如何汇总列表中所有值都为索引的列表?

How can I sum a list of lists where all the values at the a index?

例如:

let k = [ [1,1,1], [2,2,2], [3,3,3] ]
sumFoo k
> [ 6, 6, 6]


我知道我可以将两个列表总结为:


I know that I can sum two lists as:

zipWith (+) [1,2,3] [2,3,4]

但是列表列表呢?我尝试过类似的事情:

But what about a list of list? I tried something like:

foldr (\xs ys -> zipWith (+) xs ys) [] k

但这给了我一个空的名单!

but that gives me an empty list!

推荐答案

您有一个表示为列表列表的矩阵,并且想要提取列总和.为此,只需转置矩阵并计算行总和:

You have a matrix represented as a list of lists and want to extract the column sums. To do this, simply transpose the matrix and compute the row sums:

Prelude> import Data.List
Prelude Data.List> map sum . transpose $ [ [1,1,1], [2,2,2], [3,3,3] ]
[6,6,6]

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

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