gpt4 book ai didi

julia - 将多行字符串解析为数组

转载 作者:行者123 更新时间:2023-12-01 22:54:47 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

关于julia - 将多行字符串解析为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23959055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com