首页 文章

在map函数中获取Seq / Vector的索引

提问于
浏览
0

我有一个Seq [文章]

我想映射它们,但不知何故可以访问序列中文章的位置 .

因此,如果Seq包含(Article1,Article2,Article3,Article4),我想做这样的事情:

mySeq.map { article =>

   val index = article.getPositionInSeq  // <- obviously this is not defined

   //if index odd {}
   //if index even {}

}

我知道Vector已被索引,并且在其上定义了一个索引函数,它给出了Vector的范围(在我的例子中,为0..3),但是如何获得序列中每篇文章的实际位置?谢谢

1 回答

  • 5

    使用zipWithIndex将元素序列转换为对的序列(元素,索引):

    mySeq.zipWithIndex.map { e =>
      val (element, idx) = (e._1, e._2)
    }
    

相关问题