val a: List[String] = List("0","aa","1","2","3","aa","4","5","6","7")
如何在" aa"之后获得接下来的两个元素然后将这些元素放入每个独立的列表中:
期望:
List(List("1","2"),List("4","5"))
问题2:
val b: List[String] = List("0","aa","1","2","3","#","aa","4","5","#","6","7")
如何获得" aa"之间的元素。和"#" (排除" aa"和"#")然后将这些元素放入每个独立的列表中:
期望:
List(List("1","2","3"),List("4","5"))
答案 0 :(得分:4)
您可以使用var request = {
Ids: ["id1", "id2"],
Types = ["type1", "type2"],
StoreId: "123456"
}
$http({method: 'POST',header:{Content-Type: application/json},url: targetUri,data: request}).then(function(response)
{
console.log(response)
})
和sliding
来获取tails
个相关的子列表,然后使用Iterator
来过滤掉您需要的collect
个并在一次操作中将它们转换为所需的格式:
对于第一个问题:
List
或者:
scala> val a: List[String] = List("0","aa","1","2","3","aa","4","5","6","7")
a: List[String] = List(0, aa, 1, 2, 3, aa, 4, 5, 6, 7)
scala> a.sliding(3).collect {
case "aa" :: rest => rest
}.toList
res1: List[List[String]] = List(List(1, 2), List(4, 5))
关于第二个问题:
scala> a.tails.collect {
case "aa" :: rest => rest.take(2)
}.toList
res2: List[List[String]] = List(List(1, 2), List(4, 5))
答案 1 :(得分:0)
以下是第一个问题的答案:
val a: List[String] = List("0","aa","1","2","3","aa","4","5","6","7")
def arraySplit(in : List[String], accA: List[List[String]], accB: List[String]) : List[List[String]] = in match {
case h::tail => if (h == "aa" ) arraySplit(tail, accB::accA, List()) else arraySplit(tail, accA, h::accB )
case List() => accB::accA
}
val r = arraySplit(a, List(), List())
r.reverse.tail.map(x => x.reverse.take(2) )
但这不是最佳解决方案。
答案 2 :(得分:0)
对于问题1,使用tails
会很有趣
val a: List[String] = List("0","aa","1","2","3","aa","4","5","6","7")
a.tails.toList.filter(_.headOption == Some("aa")).map(_.drop(1).take(2))
>> List[Seq[String]] = List(List("1", "2"), List("4", "5"))