[英]last element of array matching scala
Good afternoon! 下午好! I'm using Scala and I want to match first three element of a list and the last one, no matter how much of them are in the list.
我正在使用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 _)
But I get : error: bad use of _* (a sequence pattern must be the last pattern)
I understand why I get it, but how can I avoid? 但是我得到了:
error: bad use of _* (a sequence pattern must be the last pattern)
我知道为什么得到它,但是如何避免呢?
My use case is that I'm reading from hdfs, and every file has exact N (N is constant and equal for all files) columns, so I want to match only some of them, without writing something like case Array(item1, item2 , ..., itemN) => List(item1, item2, itemK, itemN)
我的用例是我正在从hdfs中读取数据,并且每个文件都具有精确的N(N个常量,并且对于所有文件均相等)列,因此我只希望匹配其中一些,而无需编写
case Array(item1, item2 , ..., itemN) => List(item1, item2, itemK, itemN)
Thank you! 谢谢!
You do not need to convert lists to Arrays, because lists are designed for pattern matching. 您不需要将列表转换为数组,因为列表是为模式匹配而设计的。
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))
Or even more concise solution suggested by Kolmar 甚至是Kolmar建议的更简洁的解决方案
scala> myList match {
case item :: site :: buyer :: (_ :+ date) => List(item, site, buyer, date)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.