简体   繁体   English

Scala过滤器列表[Int]存在于其他元组列表中

[英]Scala Filter List[Int] Which Exists in other List of Tuples

I've a two lists dest (contains:x) and points (x,y) 我有两个列表dest(包含:x)和点(x,y)

dest:List[Int] and Points:List[(Int,Int)]

I want to filter elements in the dest, if it exists in points (x==points._1) i 我想过滤dest中的元素,如果它存在于点(x == points._1) i中

var newl:List[Int] = List()
for(x<-dest) if(!points.filter(_._1==x).isEmpty) newl=newl:+x

I feel like there must be a better concise way with exists but tuple making it complex. 我觉得必须有一个更好的简洁方式与存在但元组使它复杂。 So whats the best way to do the above? 那么最好的方法是什么呢?

Here is a concise way: 这是一个简洁的方法:

val dest= List(1,2,4,5)
val points = List((1,3), (2,3) , (3,4))
val newl = dest.filter{d => points.exists(_._1 == d)} // returns List(1, 2)

The following is even better order of complexity wise: 以下是复杂性更好的顺序:

val dest= List(1,2,4,5)
val points = List((1,3), (2,3) , (3,4))
val xs = points.map{_._1}.toSet
val newl = dest.filter(xs.contains(_))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM