如何对给定组大小的列表进行分区?

编程入门 行业动态 更新时间:2024-10-26 18:26:12
本文介绍了如何对给定组大小的列表进行分区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找对列表(或seq)进行分区的最佳方法,以使组具有给定的大小. 对于前.假设我想将尺寸2分组(虽然可以是其他任何数字):

I'm looking for the best way to partition a list (or seq) so that groups have a given size. for ex. let's say I want to group with size 2 (this could be any other number though):

let xs = [(a,b,c); (a,b,d); (y,z,y); (w,y,z); (n,y,z)] let grouped = partitionBySize 2 input // => [[(a,b,c);(a,b,d)]; [(y,z,y);(w,y,z)]; [(n,y,z)]]

实现partitionBySize的明显方法是将位置添加到输入列表中的每个元组,使其变为

The obvious way to implement partitionBySize would be by adding the position to every tuple in the input list so that it becomes

[(0,a,b,c), (1,a,b,d), (2,y,z,y), (3,w,y,z), (4,n,y,z)]

,然后将GroupBy与

and then use GroupBy with

xs |> Seq.ofList |> Seq.GroupBy (function | (i,_,_,_) -> i - (i % n))

但是,这种解决方案在我看来并不十分优雅. 有没有更好的方法来实现此功能(也许带有内置功能)?

However this solution doesn't look very elegant to me. Is there a better way to implement this function (maybe with a built-in function)?

推荐答案

这是一个尾部递归函数,它遍历列表一次.

Here's a tail-recursive function that traverses the list once.

let chunksOf n items = let rec loop i acc items = seq { match i, items, acc with //exit if chunk size is zero or input list is empty | _, [], [] | 0, _, [] -> () //counter=0 so yield group and continue looping | 0, _, _::_ -> yield List.rev acc; yield! loop n [] items //decrement counter, add head to group, and loop through tail | _, h::t, _ -> yield! loop (i-1) (h::acc) t //reached the end of input list, yield accumulated elements //handles items.Length % n <> 0 | _, [], _ -> yield List.rev acc } loop n [] items

用法

[1; 2; 3; 4; 5] |> chunksOf 2 |> Seq.toList //[[1; 2]; [3; 4]; [5]]

我喜欢Tomas方法的优雅之处,但是我使用了1000万个元素的输入列表对我们的两个函数进行了基准测试.这个时间是9秒,而他的时间是22秒.当然,正如他所承认的那样,最有效的方法可能涉及数组/循环.

I like the elegance of Tomas' approach, but I benchmarked both our functions using an input list of 10 million elements. This one clocked in at 9 secs vs 22 for his. Of course, as he admitted, the most efficient method would probably involve arrays/loops.

更多推荐

如何对给定组大小的列表进行分区?

本文发布于:2023-10-24 08:26:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523441.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分区   大小   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!