F# split sequence into sub lists on every nth element

后端 未结 8 863
时光说笑
时光说笑 2020-12-06 11:23

Say I have a sequence of 100 elements. Every 10th element I want a new list of the previous 10 elements. In this case I will end up with a list of 10 sublists.

Seq.t

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 12:06

    This is not bad:

    let splitEach n s =
        seq {
            let r = ResizeArray<_>()
            for x in s do
                r.Add(x)
                if r.Count = n then
                    yield r.ToArray()
                    r.Clear()
            if r.Count <> 0 then
                yield r.ToArray()
        }
    
    let s = splitEach 5 [1..17]
    for a in s do
        printfn "%A" a
    (*
    [|1; 2; 3; 4; 5|]
    [|6; 7; 8; 9; 10|]
    [|11; 12; 13; 14; 15|]
    [|16; 17|]
    *)
    

提交回复
热议问题