Scala - 根据列表的出现次数修改列表中的字符串

时间:2015-01-07 22:49:15

标签: string list scala increment

另一个Scala新手问题,因为我没有得到如何以功能方式实现这一点(主要来自脚本语言背景):

我有一个字符串列表:

val food-list = List("banana-name", "orange-name", "orange-num", "orange-name", "orange-num", "grape-name")

如果它们被复制,我想在字符串中添加一个递增的数字,并在类似于输入列表的列表中得到它,如下所示:

List("banana-name", "orange1-name", "orange1-num", "orange2-name", "orange2-num", "grape-name")

我已将它们分组以获得对它们的计数:

val freqs = list.groupBy(identity).mapValues(v => List.range(1, v.length + 1))

这给了我:

Map(orange-num -> List(1, 2), banana-name -> List(1), grape-name -> List(1), orange-name -> List(1, 2))

列表的顺序很重要(它应该是food-list的原始顺序)所以我知道在这一点上使用Map会有问题。我觉得最接近解决方案的是:

food-list.map{l =>

    if (freqs(l).length > 1){

            freqs(l).map(n => 
                           l.split("-")(0) + n.toString + "-" + l.split("-")(1))

    } else {
        l
    }
}

这当然给了我一个不稳定的输出,因为我从freqs

中的单词值映射频率列表

List(banana-name, List(orange1-name, orange2-name), List(orange1-num, orange2-num), List(orange1-name, orange2-name), List(orange1-num, orange2-num), grape-name)

如何在不使用笨拙的for循环和计数器的情况下以Scala fp方式完成此操作?

3 个答案:

答案 0 :(得分:3)

如果索引很重要,有时最好使用zipWithIndex显式跟踪它们(非常类似于Python的enumerate):

food-list.zipWithIndex.groupBy(_._1).values.toList.flatMap{
  //if only one entry in this group, don't change the values
  //x is actually a tuple, could write case (str, idx) :: Nil => (str, idx) :: Nil
  case x :: Nil => x :: Nil
  //case where there are duplicate strings
  case xs => xs.zipWithIndex.map {
    //idx is index in the original list, n is index in the new list i.e. count
    case ((str, idx), n) =>
      //destructuring assignment, like python's (fruit, suffix) = ...
      val Array(fruit, suffix) = str.split("-")
      //string interpolation, returning a tuple
      (s"$fruit${n+1}-$suffix", idx)
  }
//We now have our list of (string, index) pairs;
//sort them and map to a list of just strings
}.sortBy(_._2).map(_._1)

答案 1 :(得分:3)

高效而简单:

val food = List("banana-name", "orange-name", "orange-num", 
             "orange-name", "orange-num", "grape-name")

def replaceName(s: String, n: Int) = {
  val tokens = s.split("-")
  tokens(0) + n + "-" + tokens(1)
}

val indicesMap = scala.collection.mutable.HashMap.empty[String, Int]
val res = food.map { name =>
  {
    val n = indicesMap.getOrElse(name, 1)
    indicesMap += (name -> (n + 1))
    replaceName(name, n)
  }
}

答案 2 :(得分:0)

Here试图通过foldLeft提供您的期望:

foodList.foldLeft((List[String](), Map[String, Int]()))//initial value
    ((a/*accumulator, list, map*/, v/*value from the list*/)=>
         if (a._2.isDefinedAt(v))//already seen
             (s"$v+${a._2(v)}" :: a._1, a._2.updated(v, a._2(v) + 1))
         else
             (v::a._1, a._2.updated(v, 1)))
    ._1/*select the list*/.reverse/*because we created in the opposite order*/