在 Scala 中组合两个列表
从 List[(Int, String)
形式的 2 个列表中:
l1 = List((1,"a"),(3,"b"))
l2 = List((3,"a"),(4,"c"))
如何将 String
与 String
相同的 Integer
组合起来获取第三个列表:
l3 = List((4,"a"),(3,"b"),(4,"c"))
现在我正在遍历两个列表并添加字符串是否相同,但我认为应该有一个带有模式匹配的简单解决方案。
From 2 lists of the form List[(Int, String)
:
l1 = List((1,"a"),(3,"b"))
l2 = List((3,"a"),(4,"c"))
how can I combine the Integer
s where the String
s are the same to get this third list:
l3 = List((4,"a"),(3,"b"),(4,"c"))
Right now I'm traversing both of the lists and adding if the strings are the same, but I think there should be a simple solution with pattern matching.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
但我认为有一种更优雅的方法来完成更新部分。
But I suppose there is a more elegant way to do the
updated
part.怎么样,
在 REPL 上稍微解压一下有助于显示发生了什么,
How about,
Unpacking this a little on the REPL helps to show what's going on,
使用 Scalaz,这很容易。
|+|
方法在所有存在Semigroup[T]
实现的T
类型上公开。碰巧Map[String, Int]
的半群正是您想要的。With Scalaz, this is a snap.
The
|+|
method is exposed on all typesT
for which there exists an implementation ofSemigroup[T]
. And it just so happens that the semigroup forMap[String, Int]
is exactly what you want.请注意,使用此解决方案时,列表将被遍历两次。
Note that with this solution, the lists are traversed twice.
另一个不透明的
one双线,其效率值得怀疑,但功效却不容置疑:Another opaque
onetwo-liner of questionable efficiency yet indubitable efficacy:使用
Scala 2.13
的新 Miles Sabin 的答案 的替代方案href="https://www.scala-lang.org/api/2.13.x/scala/collection/immutable/List.html#groupMapReduce[K,B](key:A=%3EK)(f:A= %3EB)(reduce:(B,B)=%3EB):scala.collection.immutable.Map[K,B]" rel="nofollow noreferrer">groupMapReduce 方法(如其名称所示)建议)相当于(更有效)的groupBy
,后跟mapValues
和reduce
步骤:此:
前置
l1
到l2
group
元素他们的第二个元组部分(组部分groupMapReduce)将分组值映射到其第一个元组部分(组MapReduce 的映射部分)
reduce
s 值 (_ + _
) 通过求和来减少(减少 groupMapReduce 的一部分)最后
交换
元组' 部分。这是等效版本 通过以下列表一次性执行(对于组/映射/减少部分):
An alternative to Miles Sabin's answer using
Scala 2.13
's new groupMapReduce method which is (as its name suggests) an equivalent (more efficient) of agroupBy
followed bymapValues
and areduce
step:This:
prepends
l1
tol2
group
s elements based on their second tuple part (group part of groupMapReduce)map
s grouped values to their first tuple part (map part of groupMapReduce)reduce
s values (_ + _
) by summing them (reduce part of groupMapReduce)and finally
swap
s tuples' parts.This is an equivalent version performed in one pass (for the group/map/reduce part) through the List of: