如何根据scala中的谓词dropFirst取第一项

时间:2016-07-03 08:09:40

标签: scala

我将这些元素放在列表中

val list = (1,2,3,0, 0)

我需要将此列表拆分为两个列表。

val list1 = (1)
val list2 = (2, 3, 0, 0)

第一个列表包含一个不是0的项目,第二个列表包含其余项目。

修复以下代码,因此list1 never contains 0list1 :: list2 == list

val list = (1, 2, 0, 3, 0).shuffle

val list1 = list(0)
val list2 = list drop 1

与此类似:How should I remove the first occurrence of an object from a list in Scala?

2 个答案:

答案 0 :(得分:2)

我将从以下函数开始:

def sep(l: List[Int]) = 
  (l.find(_ != 0).toList, 
   l.takeWhile(_ == 0) ::: l.dropWhile(_ == 0).tail)

如果存在解决方案,它将返回您需要的内容:

sep(List(0, 1, 0, 2, 3)) -> (List(1),List(0, 0, 2, 3))
sep(List(1, 4, 0, 2, 3)) -> (List(1),List(4, 0, 2, 3))
sep(List(0, 0, 4, 5))    -> (List(4),List(0, 0, 5))

但是如果你有List(0,0) ...下一步是递归写它,所以它只使用一次迭代。

答案 1 :(得分:0)

这样做的方法很多,这是我的:

val list = List(0,1,0,3,2)
val list1 = List(list.find(_!=0).get)
val list2 = list.filter( _!=list1(0) )

结束结果(Scala REPL)

list: List[Int] = List(0, 1, 0, 3, 2)
list1: List[Int] = List(1)
list2: List[Int] = List(0, 0, 3, 2)

请注意,此代码假定list列出了一个非零成员。

更新(根据@ theArchetypalPaul的评论)以支持具有非唯一非零成员的列表:

val temp = list.span( _ == 0 )
val list1 = List(temp._2.head)
val list2 = temp._1 ++ temp._2.tail