我试图抓住朱莉娅,来自Python.目前正在解决一些Project Euler问题,我在Julia中使用Python解决了这个问题,以便更好地理解语言.我做了很多事情(在Project Euler和现实生活中)是将一个大的多线数据对象解析成一个数组.例如,如果我有数据
data = """1 2 3 4
5 6 7 8
9 0 1 2"""
Run Code Online (Sandbox Code Playgroud)
在python我可能会这样做
def parse(input):
output = []
for line in input.splitlines():
output.append(map(int,line.split()))
return np.array(output)
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止在朱莉娅所拥有的:
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
Run Code Online (Sandbox Code Playgroud)
什么是朱莉娅版的"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
Run Code Online (Sandbox Code Playgroud)