【问题标题】:Parse a multi-line string into an array将多行字符串解析为数组
【发布时间】:2014-05-31 00:53:53
【问题描述】:

我试图了解来自 Python 的 Julia。目前正在解决我在 Julia 中使用 Python 解决的一些 Project Euler 问题,以便更好地了解该语言。我经常做的一件事(在 Project Euler 和现实生活中)是将一个大的多行数据对象解析为一个数组。例如,如果我有数据

data = """1 2 3 4
5 6 7 8
9 0 1 2"""

在python中我可能会这样做

def parse(input):
    output = []
    for line in input.splitlines():
         output.append(map(int,line.split()))
    return np.array(output)

这是我目前在 Julia 中所拥有的:

function parse(input)
    nrow = ncol = 0
    # Count first
    for row=split(input,'\n')
        nrow += 1
        ncol = max(ncol,length(split(row)))
    end

    output = zeros(Int64,(nrow,ncol))
    for (i,row) in enumerate(split(input,'\n'))
        for (j,word) in enumerate(split(row))
            output[i,j] = int(word)
        end
    end
    return output
end

“pythonic”的 Julia 版本叫什么?不管是什么,我不认为我在做。我很确定有一种方法可以(1)不必两次传递数据,(2)不必那么具体地分配数组。我已经尝试了一点 hcat/vcat,但没有运气。

欢迎提出解决此问题的建议。我也对适当的 Julia 风格(julia-onic?)和一般语言使用实践的参考感兴趣。谢谢!

【问题讨论】:

    标签: julia


    【解决方案1】:

    readdlm 在这里非常有用。有关所有选项,请参阅文档,但这里有一个示例。

    julia> data="1 2 3 4
           5 6 7 8
           9 0 1 2"
    "1 2 3 4\n5 6 7 8\n9 0 1 2"
    
    julia> readdlm(IOBuffer(data))
    3x4 Array{Float64,2}:
     1.0  2.0  3.0  4.0
     5.0  6.0  7.0  8.0
     9.0  0.0  1.0  2.0
    
    julia> readdlm(IOBuffer(data),Int)
    3x4 Array{Int32,2}:
     1  2  3  4
     5  6  7  8
     9  0  1  2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 2016-06-13
      • 2012-10-14
      • 2017-04-04
      • 2014-03-04
      • 2019-12-25
      • 1970-01-01
      相关资源
      最近更新 更多