在Scala中合并两个列表 [英] Combining two lists in Scala
本文介绍了在Scala中合并两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从2个形式为List[(Int, String)
的列表中:
From 2 lists of the form List[(Int, String)
:
l1 = List((1,"a"),(3,"b"))
l2 = List((3,"a"),(4,"c"))
我如何结合Integer
,其中String
相同,以获得第三个列表:
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.
推荐答案
val l = l1 ::: l2
val m = Map[String, Int]()
(m /: l) {
case (map, (i, s)) => { map.updated(s, i + (map.get(s) getOrElse 0))}
}.toList // Note: Tuples are reversed.
但是我想有一种更优雅的方式来制作updated
部分.
But I suppose there is a more elegant way to do the updated
part.
这篇关于在Scala中合并两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文