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

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

问题描述

考虑以下元组列表:

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

并假设元素 (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 ;)

更新:

谢谢大家!set"解决方案似乎是更可取的解决方案.

Thanks to all! The "set"-solution seems to be the preferable one.

推荐答案

你可以用 set 试试,但是你需要声明你自己的 tuple 类来让它工作.

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 的回答让我意识到有更好的方法来做到这一点.那就是通过编写一个类似于 sortBy 的 distinctBy 方法.

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天全站免登陆