元组从列表中重复删除 [英] Tuples duplicate elimination from a list

查看:128
本文介绍了元组从列表中重复删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的元组列表:

val input= List((A,B), 
                (C,B), 
                (B,A)) 

code>(A,B)和(B,A)是相同的,因此是重复的,有效的方式最好在Scala中)以消除上面列表中的重复。这意味着所需的输出是另一个列表:

and assuming that the elements (A,B) and (B,A) are the same and therefore are duplicates, what is the efficient way (preferably in Scala) to eliminate duplicates from the list above. That means the desired output is an another list:

val deduplicated= List((A,B), 
                       (C,B)) 

提前感谢

ps:这不是家庭工作;)

p.s: this is not a home work ;)

更新:

感谢所有!

推荐答案

你可以尝试一套,但你需要声明自己的元组,使其工作。

You could try it with a set, but you need to declare your own tuple class to make it work.

case class MyTuple[A](t: (A, A)) {
  override def hashCode = t._1.hashCode + t._2.hashCode
  override def equals(other: Any) = other match {
    case MyTuple((a, b)) => a.equals(t._1) && b.equals(t._2) || a.equals(t._2) && b.equals(t._1)
    case _ => false
  }
}

val input= List(("A","B"), 
                ("C","B"), 
                ("B","A"))

val output = input.map(MyTuple.apply).toSet.toList.map((mt: MyTuple[String]) => mt.t)
println(output)

编辑:
Travis的答案让我意识到有一个更好的方法来做到这一点。这就是通过编写一个distinctBy方法来模拟sortBy。

edit: Travis's answer made me realise that there is a nicer way to do this. And that is by writing a distinctBy method that works analog to sortBy.

implicit class extList[T](list: List[T]) {
  def distinctBy[U](f: T => U): List[T] = {
    var set = Set.empty[U]
    var result = List.empty[T]
    for(t <- list) {
      val u = f(t)
      if(!set(u)) {
        result ::= t
        set += u
      }
    }
    result.reverse
  }
}

println(input.distinctBy { case (a, b) => Set((a,b), (b,a)) })

这篇关于元组从列表中重复删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆