总结列表清单? [英] Sum a list of lists?

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

问题描述





我知道我可以将两个列表合计为:

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

但是列表的列表呢?例如:

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

我试过类似的东西:

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

但是这给了我一个空的列表!



编辑:抱歉,我选择了一个不好的例子!它应该总结不同列表的相同标记。查看更新后的示例。 现在更清楚你实际需要什么:)你有一个矩阵表示为列表的列表并且想要提取列的总和。要做到这一点,只需对矩阵进行转置并计算行和:

  Prelude> import Data.List 
Prelude Data.List>地图总和。转置$ [[1,1,1],[2,2,2],[3,3,3]]
[6,6,6]


How can I sum a list of lists with?

I know that I can sum two lists as:

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

But what about a list of list? For example:

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

I tried something like:

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

but that gives me an empty list!

EDIT: Sorry I picked a bad example! It should sum over the same indicies of DIFFERENT lists. See updated example.

解决方案

EDIT: Now it's more clear what you actually need :) 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天全站免登陆