如何读取文件并跳过一些空白

如何读取文件并跳过一些空白

本文介绍了如何读取文件并跳过一些空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这类似于我的上一个问题

但是还有一个即兴创作,如果我想跳过一些空白,那么代码是怎么回事,在这种情况下是输入",例如:

but there is another improvisation, how is the code if i want to skip some white spaces, for this case is "enter", for example:

5 5 10
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
               <- this white space
3 4 4
1 2 3 4
1 2 3 4
1 2 3 4

我尽力而为,但是找不到跳过空白的方法谢谢您的帮助:)

i try to my best but couldn't find how to skip the white spacethank you for the help :)

这是答案,这要感谢拉蒙:

This is the answer, thanks to Ramon :

let readMap (path:string) =
    let lines = File.ReadAllLines path
    let [|x; y; n|] = lines.[0].Split() |> Array.map int
    let data =
        [|
            for l in (lines |> Array.toSeq |> Seq.skip 1 |> Seq.filter(System.String.IsNullOrEmpty >> not)) do
                yield l.Split()
        |]
    x,y,n,data

推荐答案

编写readMap函数的另一种方法是在列表推导中使用if表达式.我认为,如果您使用的是理解力,这实际上更具可读性(因为您不必将两种书写方式结合起来):

Another way to write your readMap function is to use if expression inside the list comprehension. I think this is actually more readable if you're using comprehensions (because you don't have to combine two ways of writing things):

let readMap (path:string) =
    let lines = File.ReadAllLines path
    let [|x; y; n|] = lines.[0].Split() |> Array.map int
    let data =
        [|
            for l in lines |> Seq.skip 1 do
                if not (System.String.IsNullOrEmpty(l)) then
                    yield l.Split()
        |]
    x,y,n,data

我还删除了对Array.toSeq的调用,因为F#允许您在期望seq的位置使用数组,而无需进行显式转换(seq实际上是IEnumerable,并且数组实现了它.)

I also removed the call to Array.toSeq, because F# allows you to use array in a place where seq is expected without an explicit conversion (seq is actually IEnumerable and array implements it).

这篇关于如何读取文件并跳过一些空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:12