我有一张地图,并使用
在地图中添加索引val indexByColName = sorted.view.zipWithIndex.toMap
如何找到特定密钥的索引?
答案 0 :(得分:1)
定义sorted
并显示您想要的输出会有所帮助,但我认为这可能会有所帮助。
scala> val sorted = Map("zero" -> 0, "one" -> 1, "two" -> 2)
sorted: scala.collection.immutable.Map[String,Int] = Map(zero -> 0, one -> 1, two -> 2)
scala> val indexByColName =sorted.view.zipWithIndex.toMap
indexByColName: scala.collection.immutable.Map[(String, Int),Int] = Map((zero,0) -> 0, (one,1) -> 1, (two,2) -> 2)
scala> indexByColName.get(("zero", 0)).get
res1: Int = 0
scala> indexByColName.get(("two", 2)).get
res3: Int = 2
答案 1 :(得分:1)
indexWhere
中的方法Array
提供了如下语义,
implicit class keyIndexing[A,B](val m: Map[A,B]) extends AnyVal {
def keyIndex(key: A, value: B) = {
m.toArray.indexWhere{ case (k,v) => key == k && value == v }
}
}
然后
val sorted = Map("a" -> 10, "b" -> 11, "c" -> 12)
scala> sorted.keyIndex("a",10)
res15: Int = 0
和非匹配(或非现有)键和值
scala> sorted.keyIndex("a",11)
res16: Int = -1
scala> sorted.keyIndex("z",11)
res19: Int = -1