将项目列表拆分为包含奇数和偶数索引项目的两个列表 [英] Splitting a list of items into two lists of odd and even indexed items

查看:103
本文介绍了将项目列表拆分为包含奇数和偶数索引项目的两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个接受列表并返回两个列表的函数:第一个包含每个奇数项,第二个包含每个偶数项。



例如,给定 [1; 2; 4; 6; 7; 9] ,我想返回 [[1; 4; 7]; [2; 6; 9]]



我已经写了这篇文章,但我不知道如何进展。

  let splitList list = 
let rec splitOdd oList list1 list2 =
match oList with
| [] - > []
| head :: tail - > splitEven tail(list1 :: head)list2
和splitEven oList list1 list2 =
match oList with
| [] - > []
| head :: tail - > splitOdd tail list1(list2 :: head)
splitOdd list [] []


解决

  let splitList list = List.foldBack(fun x (l,r) - > x :: r,l)list([],[])


I would like to make a function that accepts a list and returns two lists: the first contains every odd item, and the second contains every even item.

For example, given [1;2;4;6;7;9], I would like to return [ [1;4;7] ; [2;6;9] ].

I have written this so far and I do not know how to progress.

let splitList list =
    let rec splitOdd oList list1 list2 =
        match oList with
        | [] -> []
        | head :: tail -> splitEven tail (list1::head) list2
    and splitEven oList list1 list2 =
        match oList with
        | [] -> []
        | head :: tail -> splitOdd tail list1 (list2::head)
    splitOdd list [] []

解决方案

Implementation which does not stack-overflows:

let splitList list = List.foldBack (fun x (l,r) -> x::r, l) list ([],[])

这篇关于将项目列表拆分为包含奇数和偶数索引项目的两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆