本文介绍了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 个元素的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!