F# 将逗号分隔字符串列表转换为整数列表
我有一个这样的数据集F# 将逗号分隔字符串列表转换为整数列表,f#,F#,我有一个这样的数据集 1,2 3,4 5,6 7,8 9,0 当我使用ReadAllLines读取它时,我得到一个字符串数组。到目前为止,我已经将一个字符串转换为一个列表数组,其中包含以下字符串 [["1";"2"];["3";"4"]... etc 我需要最后一步来获取此[[1;1;4]…等 我现在的代码: 模块数据= 让加载(路径:字符串)(文件名:字符串)= System.IO.File.ReadAllLines(路径+“\”+文件名) |>数组.toList |>Seq.map(趣味
1,2
3,4
5,6
7,8
9,0
当我使用ReadAllLines读取它时,我得到一个字符串数组。到目前为止,我已经将一个字符串转换为一个列表数组,其中包含以下字符串
[["1";"2"];["3";"4"]... etc
我需要最后一步来获取此[[1;1;4]…等
我现在的代码:
模块数据=
让加载(路径:字符串)(文件名:字符串)=
System.IO.File.ReadAllLines(路径+“\”+文件名)
|>数组.toList
|>Seq.map(趣味s->s.Split[|','|][124;>Array.toList)
|>Seq.map(fun s->s |>Seq.map System.Int32.Parse)
这是我测试它时返回的结果
val it : seq<seq<int>> = seq [seq [1; 2]; seq [3; 4]; seq [5; 6]]
就快到了,现在只需将序列序列转换为列表列表:
|> Seq.map Seq.toList
|> Seq.toList
您可以删除行|>数组。toList
在这种情况下,最好使用序列,然后作为最后一步转换为列表
还请注意,您可以使用System.IO.Path.Combine(Path,filename)
,它将为您处理将路径与文件名组合的逻辑
最后,您可以进行一些重构:
|> Seq.map (fun s -> s |> Seq.map System.Int32.Parse)
应用此选项可以删除lambda:
|> Seq.map (Seq.map System.Int32.Parse)
然后
可以简化为单个map
,因为x>map f>map g
相当于x>map(f>>g)
删除括号:
|> Seq.map (fun s -> s.Split [|','|] |> Seq.map System.Int32.Parse |> Seq.toList)
您可以删除中间值行
和类型批注,因为组合
需要两个字符串。以下是完整代码:
open System
module Data =
let load path filename =
IO.File.ReadAllLines(IO.Path.Combine(path, filename))
|> Seq.map (fun s -> s.Split [|','|] |> Seq.map Int32.Parse |> Seq.toList)
|> Seq.toList
使用List.map
代替Seq.map
:
[|"1,2"; "3,4"; "5,6"; "7,8"; "9,0"|]
|> Array.toList
|> List.map (fun s -> s.Split [|','|] |> Array.toList)
|> List.map (fun s -> s |> List.map System.Int32.Parse)
由于一行中有两个map
s,因此可以将它们组合起来:
[|"1,2"; "3,4"; "5,6"; "7,8"; "9,0"|]
|> Array.toList
|> List.map (fun s -> s.Split [|','|] |> Array.toList |> List.map System.Int32.Parse)
两种情况下的结果:
>
val it : int list list = [[1; 2]; [3; 4]; [5; 6]; [7; 8]; [9; 0]]
[|"1,2"; "3,4"; "5,6"; "7,8"; "9,0"|]
|> Array.toList
|> List.map (fun s -> s.Split [|','|] |> Array.toList)
|> List.map (fun s -> s |> List.map System.Int32.Parse)
[|"1,2"; "3,4"; "5,6"; "7,8"; "9,0"|]
|> Array.toList
|> List.map (fun s -> s.Split [|','|] |> Array.toList |> List.map System.Int32.Parse)
>
val it : int list list = [[1; 2]; [3; 4]; [5; 6]; [7; 8]; [9; 0]]