如何快速生成列表迭代文件(how to generate a list quickly iterating a file)

编程入门 行业动态 更新时间:2024-10-23 23:29:56
如何快速生成列表迭代文件(how to generate a list quickly iterating a file)

我来自ac#和python背景,觉得必须有更好的方法来读取文件并填充经典的F#列表。 但后来我知道af #list是不可变的。 必须有一个使用List<string>对象并调用其Add方法的替代方法。

到目前为止,我手头有:

let ptr = new StreamReader("stop-words.txt") let lst = new List<string>() let ProcessLine line = match line with | null -> false | s -> lst.Add(s) true while ProcessLine (ptr.ReadLine()) do ()

如果我在python中编写类似的东西,我会做类似的事情:

[x[:-1] for x in open('stop-words.txt')]

Me coming from a c# and python background, feels there must be a better way to read a file and populate a classic F# list. But then I know that a f# list is immutable. There must be an alternative using a List<string> object and calling its Add method.

So far what I have at hand:

let ptr = new StreamReader("stop-words.txt") let lst = new List<string>() let ProcessLine line = match line with | null -> false | s -> lst.Add(s) true while ProcessLine (ptr.ReadLine()) do ()

If I were to write the similar stuff in python I'd do something like:

[x[:-1] for x in open('stop-words.txt')]

最满意答案

简单解决方案

System.IO.File.ReadAllLines(filename) |> List.ofArray

虽然你可以写一个递归函数

let processline fname = let file = new System.IO.StreamReader("stop-words.txt") let rec dowork() = match file.ReadLine() with |null -> [] |t -> t::(dowork()) dowork()

Simple solution

System.IO.File.ReadAllLines(filename) |> List.ofArray

Although you can write a recursive function

let processline fname = let file = new System.IO.StreamReader("stop-words.txt") let rec dowork() = match file.ReadLine() with |null -> [] |t -> t::(dowork()) dowork()

更多推荐

本文发布于:2023-07-05 06:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034372.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快速   迭代   文件   列表   generate

发布评论

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

>www.elefans.com

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