簡體   English   中英

數組匹配Scala的最后一個元素

[英]last element of array matching scala

下午好! 我正在使用Scala,並且無論列表中有多少元素,我都希望匹配列表的前三個元素和最后一個元素。

val myList:List[List[Int]] = List(List(3,1,2,3,4),List(23,45,6,7,2),List(3,3,2,1,5,34,43,2),List(8,5,3,34,4,5,3,2),List(3,2,45,56))

def parse(lists: List[Int]): List[Int] = lists.toArray match{
  case Array(item, site, buyer, _*, date) => List(item, site, buyer, date)}

myList.map(parse _)

但是我得到了: error: bad use of _* (a sequence pattern must be the last pattern)我知道為什么得到它,但是如何避免呢?

我的用例是我正在從hdfs中讀取數據,並且每個文件都具有精確的N(N個常量,並且對於所有文件均相等)列,因此我只希望匹配其中一些,而無需編寫case Array(item1, item2 , ..., itemN) => List(item1, item2, itemK, itemN)

謝謝!

您不需要將列表轉換為數組,因為列表是為模式匹配而設計的。

scala> myList match { 
  case item :: site :: buyer :: tail if tail.nonEmpty => 
    item :: site :: buyer :: List(tail.last)
}
res3: List[List[Int]] = List(List(3, 1, 2, 3, 4), List(23, 45, 6, 7, 2), 
  List(3, 3, 2, 1, 5, 34, 43, 2), List(3, 2, 45, 56))

甚至是Kolmar建議的更簡潔的解決方案

scala> myList match { 
  case item :: site :: buyer :: (_ :+ date) => List(item, site, buyer, date) 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM