我的两个清单如下:
val a = List((1430299869,"A",4200), (1430299869,"A",0))
val b = List((1430302366,"B",4100), (1430302366,"B",4200), (1430302366,"B",5000), (1430302366,"B",27017), (1430302366,"B",80), (1430302366,"B",9300), (1430302366,"B",9200), (1430302366,"A",5000), (1430302366,"A",4200), (1430302366,"A",80), (1430302366,"A",443), (1430302366,"C",4100), (1430302366,"C",4200), (1430302366,"C",27017), (1430302366,"C",5000), (1430302366,"C",80))
当我使用zip两个列表时如下:
val c = a zip b
它将结果返回为
List(((1430299869,A,4200),(1430302366,B,4100)), ((1430299869,A,0),(1430302366,B,4200)))
不是所有元组列表,我如何压缩以上所有数据?
编辑
预期结果为两个列表的组合,如:
List((1430299869,"A",4200), (1430299869,"A",0),(1430302366,"B",4100), (1430302366,"B",4200), (1430302366,"B",5000), (1430302366,"B",27017), (1430302366,"B",80), (1430302366,"B",9300), (1430302366,"B",9200), (1430302366,"A",5000), (1430302366,"A",4200), (1430302366,"A",80), (1430302366,"A",443), (1430302366,"C",4100), (1430302366,"C",4200), (1430302366,"C",27017), (1430302366,"C",5000), (1430302366,"C",80))
第二次修改
我试过了:
val d = for(((a,b,c),(d,e,f)) <- (a zip b)if(b.equals(e) && c.equals(f))) yield (d,e,f)
但由于(a zip b)
而导致结果为空,但我将a zip b
替换为a ++ b
,然后显示以下错误:
构造函数无法实例化为期望的类型;
那么如何才能获得匹配的元组呢?
答案 0 :(得分:2)
只需将一个列表添加到另一个列表:
a ++ b
答案 1 :(得分:1)
在压缩(配对)列表中的所有数据时,首先考虑一个简短的输入来说明案例,
val a = (1 to 2).toList
val b = (10 to 12).toList
然后,例如,理解可以传达需求,
for (i <- a; j <- b) yield (i,j)
提供
List((1,10), (1,11), (1,12),
(2,10), (2,11), (2,12))
<强>更新强>
从OP最新更新,考虑专用过滤功能,
type triplet = (Int,String,Int)
def filtering(key: triplet, xs: List[triplet]) =
xs.filter( v => key._2 == v._2 && key._3 == v._3 )
然后将其应用于flatMap
,
a.flatMap(filtering(_, b))
List((1430302366,A,4200))
另外一个步骤是将其封装在隐式类
中implicit class OpsFilter(val keys: List[triplet]) extends AnyVal {
def filtering(xs: List[triplet]) = {
keys.flatMap ( key => xs.filter( v => key._2 == v._2 && key._3 == v._3 ))
}
}
同样,
a.filtering(b)
List((1430302366,A,4200))
答案 2 :(得分:1)
a zip b
创建a和b中的元素对列表。
您最有可能寻找的是列表连接,即a ++ b