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

2019-01-21 17:58发布

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

7条回答
Viruses.
2楼-- · 2019-01-21 18:34

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)) )
查看更多
一纸荒年 Trace。
3楼-- · 2019-01-21 18:35

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
     )
查看更多
The star\"
4楼-- · 2019-01-21 18:46

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)
查看更多
我命由我不由天
5楼-- · 2019-01-21 18:46

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 
查看更多
再贱就再见
6楼-- · 2019-01-21 18:47

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) )
查看更多
贪生不怕死
7楼-- · 2019-01-21 18:50

The proposed solutions suffer from the fact that they create intermediate collections or introduce variables which are not strictly necessary. For ultimately all you need to do is to keep track of the number of steps of an iteration. This can be done using memoizing. The resulting code might look like

myIterable map (doIndexed(someFunction))

The doIndexed-Function wraps the interior function which receives both an index an the elements of myIterable. This might be familiar to you from JavaScript.

Here is a way to achieve this purpose. Consider the following utility:

object TraversableUtil {
    class IndexMemoizingFunction[A, B](f: (Int, A) => B) extends Function1[A, B] {
        private var index = 0
        override def apply(a: A): B = {
            val ret = f(index, a)
            index += 1
            ret
        }
    }

    def doIndexed[A, B](f: (Int, A) => B): A => B = {
        new IndexMemoizingFunction(f)
    }
}

This is already all you need. You can apply this for instance as follows:

import TraversableUtil._
List('a','b','c').map(doIndexed((i, char) => char + i))

which results in the list

List(97, 99, 101)

This way, you can use the usual Traversable-functions at the expense of wrapping your effective function. The overhead is the creation of the memoizing object and the counter therein. Otherwise this solution is as good (or bad) in terms of memory or performance as using unindexed map. Enjoy!

查看更多
登录 后发表回答