我有以下两个列表 -
val a = List((HarddiskVolume1,31,1), (C:,46552070,433057), (E:,5435,1728), (_Total,46557536,434786))
val b = List(C:, E:)
我想要输出如下: O / P (C:,46552070,433057),(E:,5435,1728)
如何使用scala获得所需的输出?
答案 0 :(得分:3)
val a = List(("HarddiskVolume1",31,1), ("C:",46552070,433057), ("E:",5435,1728), ("_Total",46557536,434786))
val b = List("C:", "E:")
a.filter(x => b.contains(x._1)) // if b is large, consider making it a set.
// res0: List[(String, Int, Int)] = List((C:,46552070,433057), (E:,5435,1728))
答案 1 :(得分:2)
像这样使用collect
,
val keys = b.toSet
a collect { case z@(x,_,_) if keys(x) => z }
<强>更新强>
其他类似方法包括
for ( z <- a if keys(z._1) ) yield z
a collect { case z if keys(z._1) => z }
( a partition ( z => keys(z._1) ) )._1
答案 2 :(得分:0)
如果数据作为列表中的列表存在,则回答@Yogesh:
val aa =List(List(("HarddiskVolume1",31,1), ("C:",46552070,433057), ("E:",5435,1728), ("_Total",46557536,434786)),
List(("HarddiskVolume1",31,1), ("C:",46552070,433057), ("E:",5435,1728), ("_Total",46557536,434786))
)
val b = List("C:", "E:")
aa.map(l => l.filter(x => b.exists(_== x._1)))
与Shyamendra类似,但在列表中使用exists运算符。