How can I use map and receive an index as well in Scala?

前端 未结 8 1785
轮回少年
轮回少年 2020-12-12 23:07

Is there any List/Sequence built-in that behaves like map and provides the element\'s index as well?

相关标签:
8条回答
  • 2020-12-12 23:43

    I believe you're looking for zipWithIndex?

    scala> val ls = List("Mary", "had", "a", "little", "lamb")
    scala> ls.zipWithIndex.foreach{ case (e, i) => println(i+" "+e) }
    0 Mary
    1 had
    2 a
    3 little
    4 lamb
    

    From: http://www.artima.com/forums/flat.jsp?forum=283&thread=243570

    You also have variations like:

    for((e,i) <- List("Mary", "had", "a", "little", "lamb").zipWithIndex) println(i+" "+e)
    

    or:

    List("Mary", "had", "a", "little", "lamb").zipWithIndex.foreach( (t) => println(t._2+" "+t._1) )
    
    0 讨论(0)
  • 2020-12-12 23:44

    Or, assuming your collection has constant access time, you could map the list of indexes instead of the actual collection:

    val ls = List("a","b","c")
    0.until(ls.length).map( i => doStuffWithElem(i,ls(i)) )
    
    0 讨论(0)
  • 2020-12-12 23:44

    Use .map in .zipWithIndex with Map data structure

    val sampleMap = Map("a" -> "hello", "b" -> "world", "c" -> "again")
    
    val result = sampleMap.zipWithIndex.map { case ((key, value), index) => 
        s"Key: $key - Value: $value with Index: $index"
    }
    

    Results

     List(
           Key: a - Value: hello with Index: 0, 
           Key: b - Value: world with Index: 1, 
           Key: c - Value: again with Index: 2
         )
    
    0 讨论(0)
  • 2020-12-12 23:50

    There is CountedIterator in 2.7.x (which you can get from a normal iterator with .counted). I believe it's been deprecated (or simply removed) in 2.8, but it's easy enough to roll your own. You do need to be able to name the iterator:

    val ci = List("These","are","words").elements.counted
    scala> ci map (i => i+"=#"+ci.count) toList
    res0: List[java.lang.String] = List(These=#0,are=#1,words=#2)
    
    0 讨论(0)
  • 2020-12-12 23:55

    If you require searching the map values as well (like I had to):

    val ls = List("a","b","c")
    val ls_index_map = ls.zipWithIndex.toMap 
    
    0 讨论(0)
  • 2020-12-13 00:02

    Use .map in .zipWithIndex

    val myList = List("a", "b", "c")
    
    myList.zipWithIndex.map { case (element, index) => 
       println(element, index) 
       s"${element}(${index})"
    }
    

    Result:

    List("a(0)", "b(1)", "c(2)")
    
    0 讨论(0)
提交回复
热议问题