将逗号分隔的字符串列表转换为整数列表的列表

时间:2016-03-04 05:33:02

标签: f#

我有一个像这样的数据集

1,2
3,4
5,6
7,8
9,0

当我使用ReadAllLines读取它时,我得到一个字符串数组。到目前为止,我已经将字符串转换为包含字符串的列表数组,例如

[["1";"2"];["3";"4"]... etc

我需要最后一步才能获得此[[1;1;[1;4]... etc

我的代码现在:

module Data =
    let load(path : string) (filename : string) =
        System.IO.File.ReadAllLines(path + "\" + filename) 
        |> Array.toList
        |> Seq.map (fun s -> s.Split [|','|] |> 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]]

我期待这样的事情

val zz : int list list = [[1; 2]; [3; 4]]

2 个答案:

答案 0 :(得分:5)

你几乎就在那里,现在你只需要将序列序列转换为列表列表:

|> Seq.map Seq.toList
|> Seq.toList

你可以删除行|> Array.toList,在这种情况下,它可以更好地处理序列,然后作为最后一步转换为列表。

另请注意,您可以使用System.IO.Path.Combine(path, filename)来处理将路径与文件名组合起来的逻辑。

最后你可以做一些重构:

|> Seq.map (fun s -> s |> Seq.map System.Int32.Parse)

应用eta reduction你可以删除lambda:

|> Seq.map (Seq.map System.Int32.Parse)

然后

|> Seq.map (fun s -> s.Split [|','|] |> Array.toList)
|> Seq.map (fun s -> s |> Seq.map System.Int32.Parse)
|> Seq.map Seq.toList

可简化为单map,因为x |> map f |> map g相当于x |> map (f >> g)

|> Seq.map ( (fun s -> s.Split [|','|]) >> Seq.map System.Int32.Parse >> Seq.toList)

消除括号:

|> Seq.map (fun s -> s.Split [|','|] |> Seq.map System.Int32.Parse |> Seq.toList)

您可以删除中间值lines并输入注释,因为Combine需要两个字符串。这是完整的代码:

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

答案 1 :(得分:3)

使用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,因此可以将它们组合在一起:

[|"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]]
相关问题