任何人都可以解释:如何在子列表中拆分列表:
列表:
scala> val ls = List("P ", "PP ", "PP ", "PP ", "P ", "PP ", "PP ", "P ")
或者
scala> val ls = List("P", "PP", "PP", "PP", "P", "PP", "PP", "P")
子列表:
List("P", "PP", "PP", "PP"), List("P", "PP", "PP"), List("P")
已编辑 ::我真正想要的是在每次出现特定字符串时拆分列表!
TIA。
答案 0 :(得分:4)
使用Include Irvine32.inc
n=1000
n_terminal=31
; terminal compare value is min(sqrt(n), 0FFFFh) (last value to process)
; no point to sieve beyond sqrt(n), because first unset multiply is
; sqrt(n)*sqrt(n) = n => beyond array
; and no point to sieve 10000h, because 10000h*10000h is out of 32b
.data
prime BYTE n DUP(?)
.code
main PROC
; fill array with "1" (from number 2 to n)
mov edi,OFFSET prime+2
mov ecx,n-2
mov eax,1 ; eax=1 will be used also later (also ah=0)
rep stosb
; set "0" and "1" as non-prime too
mov WORD PTR [prime],cx ; (cx == 0 after "rep stosb")
; set "0" to all other non-primes by sieving
mov esi,eax ; esi=1, start the loop as if "1" was handled last
sieve_loop:
inc esi ; next number to test
; sqrt(n) is enough to process, beyond that n <= number*number => out of array
cmp esi,n_terminal
ja sieve_end ; out of table, end sieving
cmp prime[esi],al ; compare with "1"
jne sieve_loop ; not a prime, don't flip the rest of sieve
; esi is prime, flip the other multiplies of it, starting from esi*esi (!)
mov edi,esi ; esi*esi as smaller multiples are already covered by
imul edi,edi ; smaller prime numbers sieving the array before
flip_loop:
cmp edi,n ; check if the multiply points beyond table
jae sieve_loop ; if yes, continue main loop with next "prime"
mov prime[edi],ah ; set this number to "0" (not prime)
add edi,esi ; edi = next multiply of esi prime
jmp flip_loop
sieve_end:
; print all primes starting from 2
mov esi,eax ; esi = 1, as if "1" was handled last
print_loop:
inc esi ; while (++number < n)
cmp esi,n
jae end_print_loop
cmp BYTE PTR prime[esi],1 ; eax/al is modified from "WriteDec"
jne print_loop ; not a prime number, loop
; esi is prime number, print it
mov eax,esi
call WriteDec ; these two calls must preserve esi
call Crlf
jmp print_loop
end_print_loop:
exit
main ENDP
END main
的另一个选项:
foldLeft
答案 1 :(得分:2)
递归(但不是尾递归)解决方案:
val l = List("P ", "PP ", "PP ", "PP ", "P ", "PP ", "PP ", "P ")
def splitBy(l: List[String], s: String): List[List[String]] = {
l.splitAt(l.lastIndexOf(s)) match {
case (Nil, tail) => List(tail)
case (head, tail) => splitBy(head, s) :+ tail
}
}
splitBy(l, "P ") // List(List(P , PP , PP , PP ), List(P , PP , PP ), List(P ))
Tail Recursive version:
val l = List("P", "PP", "PP", "PP", "P", "PP", "PP", "P")
def splitBy(result: List[List[String]], l: List[String], s: String): List[List[String]] = {
l.splitAt(l.lastIndexOf(s)) match {
case (Nil, y) => List(y) ::: result
case (x, y) => splitBy(List(y) ::: result, x, s)
}
}
println(splitBy(Nil, l, "P"))
答案 2 :(得分:1)
sed