F#在第n个元素上将序列拆分为子列表 [英] F# split sequence into sub lists on every nth element
本文介绍了F#在第n个元素上将序列拆分为子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有100个元素的序列.每隔10个元素,我都希望获得前10个元素的新列表.在这种情况下,我将得到一个包含10个子列表的列表.
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.take(10)看起来很有希望,如何反复调用它以返回列表列表?
Seq.take(10) looks promising, how can I repeatedly call it to return a list of lists?
推荐答案
这还不错:
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|]
*)
这篇关于F#在第n个元素上将序列拆分为子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文