在 Scala 中对两个列表求和的最简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8601041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:45:26  来源:igfitidea点击:

Simplest way to sum two Lists in Scala?

scalaclojure

提问by Phil

I have two lists, I want to sum each element in list A with the element in list B, producing a new list.

我有两个列表,我想将列表 A 中的每个元素与列表 B 中的元素相加,生成一个新列表。

I can do it with:

我可以这样做:

List(1,2).zip(List(5,5)).map(t => t._1 + t._2)

Is there any simpler or neater way to do this in Scala?

在 Scala 中有没有更简单或更简洁的方法来做到这一点?

In Clojure I can just do:

在 Clojure 中,我可以这样做:

(map + [1 2 3] [4 5 6])

回答by missingfaktor

For two lists:

对于两个列表:

(List(1,2), List(5,5)).zipped.map(_ + _)

For three lists:

对于三个列表:

(List(1,2), List(5,5), List(9, 4)).zipped.map(_ + _ + _)

For n lists:

对于 n 个列表:

List(List(1, 2), List(5, 5), List(9, 4), List(6, 3)).transpose.map(_.sum)

回答by Heiko Seeberger

missingfaktor's answer is what I would have recommended, too.

missingfaktor 的回答也是我推荐的。

But you could even improve your snippet to get rid of using the clumsy _1, _2:

但是您甚至可以改进您的代码段以摆脱使用笨拙的 _1、_2:

List(1,2) zip List(5,5) map { case (a, b) => a + b }

回答by thoredge

Another way to simplify:

另一种简化方法:

import Function.tupled
List(1,2).zip(List(5,5)) map tupled {_ + _}

回答by ZhekaKozlov

In Scalaz:

在斯卡拉兹:

List(1,2) merge List(5,5)

Works also for lists with different sizes: List(1,2,3) merge List(5,5)will return List(6,7,3)

也适用于不同大小的列表:List(1,2,3) merge List(5,5)将返回List(6,7,3)