简体   繁体   English

zipWithIndex有无大小写

[英]zipWithIndex with and without case

How are the following 2 pieces of code equivalent? 以下两段代码如何等效? (how does case work) (案件如何运作)

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

and

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

You are probably confused by wrong names in second sample. 您可能对第二个示例中的错误名称感到困惑。 I changed it to: 我将其更改为:

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

This is short version of: 这是以下内容的简称:

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

I preferred the first one, since every element here is case (rowAndIndex, r), check it every time seems unnecessary. 我更喜欢第一个,因为这里的每个元素都是大小写(rowAndIndex,r),因此每次检查都显得不必要。

And, it seems that you actually don't want the first 'index', why not just use: 而且,似乎您实际上并不想要第一个“索引”,为什么不直接使用:

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

By the way, I just put following code to http://scalass.com/tryout 顺便说一句,我只是将以下代码放入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)

The output is all like 输出都像

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

This is what you want, right? 这就是你想要的,对吗?

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

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