list - 按元素值拆分列表
问题描述
我想根据特定值将字符串分成几个块。
例如列表[1; 2; 3; 0; 2; 4; 0; 5; 6; 0; 7]
和检查元素0
应该返回[[1; 2; 3]; [2; 4]; [5; 6]; [7]]
如果下一个元素低于当前元素,我找到了一种拆分列表的方法
[1; 2; 3; 0; 2; 4; 0; 5; 6; 0; 7]
会回来[[1; 2; 3]; [0; 2; 4]; [0; 5; 6]; [0; 7]]
这是方法order ascending split
let split2 lst =
let folder (a, b) (cur, acc) =
match a with
| _ when a < b -> a::cur, acc
| _ -> [a], cur::acc
let result = List.foldBack folder (List.pairwise lst) ([List.last lst], [])
(fst result)::(snd result)
printfn "%A" (split2 thelist)
这是我的修改:
let folder (a) (cur, acc) =
match a with
| _ when a <> 0 -> a::cur, acc
| _ -> [], cur::acc
let split lst =
let result = List.foldBack folder (lst) ([], [])
(fst result)::(snd result)
printfn "%A" (split thelist)
我不再需要了,pairwise
因为我只逐个元素地检查,但是定义为的current
和让我感到困惑,我不确定解决方案是否正确,即使我得到了所需的输出acumulator
[]
有没有更简单的解决方案?
解决方案
我会这样做
let list = [1; 2; 3; 0; 2; 4; 0; 0; 5; 6; 0; 7]
list
|> Seq.fold (fun state number ->
match number with
| 0 -> []::state
| x ->
match state with
| [] -> [] // never here, actually
| h::t -> [x::h]@t
)
[[]]
|> List.map List.rev
|> List.rev
|> List.filter (List.isEmpty >> not)
因此,您的状态是一个列表列表(无论如何,这是您最终想要的)。您需要反转内部列表,然后是外部列表(如果您关心顺序)。
我在最后添加了过滤器来处理连续 0 的结果,这会产生空列表。您可以在文件夹函数中处理它,它只会使代码比现在更冗长。
推荐阅读
- react-native - react-native 自定义文本省略号以在省略号后添加“更多”
- python - 用熊猫中多级列的不同值替换值
- python - 如何根据日期时间过滤文件?
- bash - 解析命令输出并构建 bash 键值
- telegram-bot - 如何删除电报机器人自己的消息?
- java - 将字符串列表作为 Cucumber 参数传递
- c# - 如何在unity3d中在com上方添加力?
- python - 未找到页面 (404) 正在报告
- facebook-graph-api - 如何从服务器端获取 Instagram Graph API 用户访问令牌
- node.js - 运行 npm login 命令时出现 403 错误?