繁体   English   中英

zipWithIndex有无大小写

[英]zipWithIndex with and without case

以下两段代码如何等效? (案件如何运作)

 list.zipWithIndex.flatMap{ 
     rowAndIndex =>
     rowAndIndex._1.zipWithIndex
}

list.zipWithIndex.flatMap {
    case (rowAndIndex, r) =>
     rowAndIndex.zipWithIndex
}

您可能对第二个示例中的错误名称感到困惑。 我将其更改为:

list.zipWithIndex.flatMap {
    case (row, index) =>
     row.zipWithIndex
}

这是以下内容的简称:

list.zipWithIndex.flatMap { rowAndIndex => 
  rowAndIndex match {
    case (row, index) => row.zipWithIndex
  }
}

我更喜欢第一个,因为这里的每个元素都是大小写(rowAndIndex,r),因此每次检查都显得不必要。

而且,似乎您实际上并不想要第一个“索引”,为什么不直接使用:

list.map(s => s.zipWithIndex).flatten

顺便说一句,我只是将以下代码放入http://scalass.com/tryout

val list = List("Abby", "Jim", "Tony")

val a = list.zipWithIndex.flatMap({a =>
  a._1.zipWithIndex})
println(a)

val b = list.zipWithIndex.flatMap({case (rowAndIndex, r) =>
  rowAndIndex.zipWithIndex})
println(b)

val d = list.map(s => s.zipWithIndex).flatten
println(d)

输出都像

List((A,0), (b,1), (b,2), (y,3), (J,0), (i,1), (m,2), (T,0), (o,1), (n,2), (y,3))

这就是你想要的,对吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM