[scala] 어떻게지도를 사용하고 Scala에서도 인덱스를받을 수 있습니까?

map요소의 인덱스 처럼 작동 하고 제공하는 내장 된 List / Sequence가 있습니까?



답변

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

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

또한 다음과 같은 변형이 있습니다.

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

또는:

List("Mary", "had", "a", "little", "lamb").zipWithIndex.foreach( (t) => println(t._2+" "+t._1) )


답변

사용하다 . 지도 한다. zipWithIndex

val myList = List("a", "b", "c")

myList.zipWithIndex.map { case (element, index) =>
   println(element, index)
   s"${element}(${index})"
}

결과:

List("a(0)", "b(1)", "c(2)")


답변

제안 된 솔루션은 중간 컬렉션을 생성하거나 엄격하게 필요하지 않은 변수를 도입한다는 사실로 어려움을 겪습니다. 궁극적으로해야 할 일은 반복 단계 수를 추적하는 것입니다. 이것은 메모를 사용하여 수행 할 수 있습니다. 결과 코드는 다음과 같습니다.

myIterable map (doIndexed(someFunction))

doIndexedα- 함수 인덱스 요소 모두를 수신하는 기능을 내부 랩 myIterable. 이것은 JavaScript에서 친숙 할 것입니다.

이 목적을 달성하는 방법이 있습니다. 다음 유틸리티를 고려하십시오.

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)
    }
}

이것은 이미 필요한 전부입니다. 예를 들어 다음과 같이 적용 할 수 있습니다.

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

결과 목록

List(97, 99, 101)

이렇게하면 효과적인 함수를 래핑하는 대신 일반적인 Traversable 함수를 사용할 수 있습니다. 오버 헤드는 메모 개체와 그 안에 카운터를 만드는 것입니다. 그렇지 않으면이 솔루션은 unindexed를 사용하는 것만 큼 메모리 나 성능면에서 좋거나 나쁩니다 map. 즐겨!


답변

CountedIterator(.counted 당신이 정상 반복자에서 얻을 수있는) 2.7.x에서. 나는 2.8에서 더 이상 사용되지 않거나 단순히 제거되었다고 생각하지만 직접 롤링하는 것은 쉽습니다. 반복자의 이름을 지정할 수 있어야합니다.

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)


답변

또는 컬렉션에 일정한 액세스 시간이 있다고 가정하면 실제 컬렉션 대신 인덱스 목록을 매핑 할 수 있습니다.

val ls = List("a","b","c")
0.until(ls.length).map( i => doStuffWithElem(i,ls(i)) )


답변

지도 데이터 구조와 함께 .zipWithIndex 에서 .map 사용

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"
}

결과

 List(
       Key: a - Value: hello with Index: 0,
       Key: b - Value: world with Index: 1,
       Key: c - Value: again with Index: 2
     )


답변

이를 수행하는 방법에는 두 가지가 있습니다.

ZipWithIndex : 0부터 자동으로 카운터를 생성합니다.

  // zipWithIndex with a map.
  val days = List("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
  days.zipWithIndex.map {
        case (day, count) => println(s"$count is $day")
  }
  // Or use it simply with a for.
  for ((day, count) <- days.zipWithIndex) {
        println(s"$count is $day")
  }

두 코드의 출력은 다음과 같습니다.

0 is Sun
1 is Mon
2 is Tue
3 is Wed
4 is Thu
5 is Fri
6 is Sat

Zip : Stream과 함께 zip 방식을 사용하여 카운터를 생성합니다. 이것은 시작 값을 제어하는 ​​방법을 제공합니다.

for ((day, count) <- days.zip(Stream from 1)) {
  println(s"$count is $day")
}

결과:

1 is Sun
2 is Mon
3 is Tue
4 is Wed
5 is Thu
6 is Fri
7 is Sat