簡體   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