简体   繁体   English

将Scala列表的每个元素与列表中的其余元素进行比较

[英]Compare each element of Scala list against rest of elements in the list

I have a list of Custom objects which will be compared against rest of the objects in the same list. 我有一个Custom对象列表,它将与同一列表中的其余对象进行比较。

My current approach: Currently i take one element from a the list using foreach loop,run another foreach loop to look through the list for elements that are similar to the taken object. 我目前的方法:目前我使用foreach循环从列表中获取一个元素,运行另一个foreach循环以查看列表中与被摄对象类似的元素。

case class TestOb(name:String,pos:Vector[Int])

val lis:List[TestOb] = null

lis.foreach{i=>
    val ref = i._2
    lis.foreach{j=>
        val current = j._2
        //compare ref and current.
    }
}

Is there any other efficient way to do this iteration in Scala within same list without having two foreach loops? 有没有其他有效的方法在Scala中在同一列表中进行此迭代而没有两个foreach循环?

Have you tried using the for -loop? 你尝试过使用for -loop吗?

for( a <- lis; b <- lis) {
  // do stuff with a and b
}

For further convinience here an easy example to get an idea of the iteration going on behind the scenes: 为了进一步方便,这里有一个简单的例子来了解幕后的迭代:

scala> val list = 1 to 3
list: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3)
scala> for(a <- list; b <- list) println(a+" - "+b)
1 - 1
1 - 2
1 - 3
2 - 1
2 - 2
2 - 3
3 - 1
3 - 2
3 - 3

For what its worth, enzymes solution would be more in line with the functional style scala embraces. 对于它的价值,酶解决方案将更符合功能风格的scala包容。

An approach to compare each element in a collection against the rest and to collect those that are similar (here identical by using == in collect ). 一种方法,用于比较集合中的每个元素与其余元素,并收集相似的元素(这里使用==collect相同)。 In order to illustrate the case consider 为了说明案例的考虑

case class C(i:Int)

and a collection where C(1) has a similar item (equality here), 和一个集合,其中C(1)有一个similar项目(这里相等),

val xs = Array( C(1),C(2),C(3),C(1),C(4) )

Hence we combine each two items, compare them and collect those similar, 因此,我们将每两项合并,比较它们并收集相似的项目,

xs.combinations(2).collect { case Array(a,b) if a == b => a }.toArray
Array(C(1))

Note combinations delivers an iterator which is consumed (iterated over) by collect . 注意combinations提供了一个迭代器,它由collect消耗(迭代)。 Also, replace == in collect with a dissimilarity function for comparing items to decide which are similar enough. 另外,在collect使用不相似函数替换==来比较项目以确定哪些足够相似。

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

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