gpt4 book ai didi

scala - takeWhile : also need first element failed the condition in scala

转载 作者:行者123 更新时间:2023-12-05 03:14:08 25 4
gpt4 key购买 nike

scala> List(1,2,3,4,5,6,7).takeWhile(i=>i<5) 
res1: List[Int] = List(1, 2, 3, 4)

如果我还需要在结果中包含 5 怎么办?

最佳答案

假设你将要使用的函数比取前 5 个元素更复杂,

你可以做到

scala> List(1,2,3,4,5,6,7)
res5: List[Int] = List(1, 2, 3, 4, 5, 6, 7)

scala> res5.takeWhile(_<5) ++ res5.dropWhile(_<5).take(1)
res7: List[Int] = List(1, 2, 3, 4, 5)

还有

scala> res5.span(_<5)
res8: (List[Int], List[Int]) = (List(1, 2, 3, 4),List(5, 6, 7))
scala> res8._1 ++ res8._2.take(1)
res10: List[Int] = List(1, 2, 3, 4, 5)

还有

scala> res5.take(res5.segmentLength(_<5, 0) + 1)
res17: List[Int] = List(1, 2, 3, 4, 5)

scala> res5.take(res5.indexWhere(_>5))
res18: List[Int] = List(1, 2, 3, 4, 5)

关于scala - takeWhile : also need first element failed the condition in scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26828190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com