JuliaJulia语言

Julia快速入门(五)多维数组 字典

2018-11-20  本文已影响28人  Julia语言

本篇代码在Julia1.0.2中测试通过

多维数组

多维数组定义

function printsum(a)
    println(summary(a), ": ", repr(a))
end

# repeat函数可以被用来扩展网格
# 这和R语言中的expand.grid()函数很类似

# hcat在第二个维度上连接,即按列的方向,即横着堆叠。
m1 = hcat(repeat([1,2],inner=[1],outer=[6]),
          repeat([1,2,3],inner=[2],outer=[2]),
          repeat([1,2,3,4],inner=[3],outer=[1]))
m1
12×3 Array{Int64,2}:
 1  1  1
 2  1  1
 1  2  1
 2  2  2
 1  3  2
 2  3  2
 1  1  3
 2  1  3
 1  2  3
 2  2  4
 1  3  4
 2  3  4

多维数组生成

# Julia还提供了更简单的创建多维数组的方式——使用comprehensions

julia> x = rand(8)
8-element Array{Float64,1}:
 0.843025
 0.869052
 0.365105
 0.699456
 0.977653
 0.994953
 0.41084
 0.809411

julia> [ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]
6-element Array{Float64,1}:
 0.736559
 0.57468
 0.685417
 0.912429
 0.8446
 0.656511

字典

Julia使用Dict(字典)来处理数据集合,使用方法和Python非常相似,除了比较奇怪的定义句法

字典的定义

function printsum(a)
    println(summary(a), ": ", repr(a))
end

# 字典可以直接初始化
a1 = Dict(1=>"one", 2=>"two")
printsum(a1)
# Dict{Int64,String} with 2 entries: Dict(2=>"two",1=>"one")

# 字典也可以直接扩展
a1[3]="three"
printsum(a1)
# Dict{Int64,String} with 3 entries: Dict(2=>"two",3=>"three",1=>"one")
# (注意字典并不会始终保持原有的元素顺序)

# 字典同样可以指定元素类型
a2 = Dict{Int64, AbstractString}()
a2[0]="zero"
printsum(a2)
# Dict{Int64,AbstractString} with 1 entry: Dict{Int64,AbstractString}(0=>"zero")

字典的操作函数

a1 = Dict(1=>"one", 2=>"two", 3=>"three")
# 正如你所想,字典应当具有的各种方法Julia都有,比如说haskey
println(haskey(a1,1))
# 程序输出: true

# 上面的表达式与下面这个等同
println(1 in keys(a1))
# 程序输出: true
# 这里keys方法创建了一个迭代器用来遍历字典中的所有键

# 和keys方法类似,values方法创建了一个遍历所有值的迭代器
printsum(values(a1)) 
# Base.ValueIterator for a Dict{Int64,String} with 3 entries: ["two", "three", "one"]

# 可以使用collect方法来获得对应的数组
printsum(collect(values(a1)))
# 3-element Array{String,1}: ["two", "three", "one"]
欢迎关注微信公众账号Julia语言.jpg

点击阅读原文可查看历史文章

上一篇 下一篇

猜你喜欢

热点阅读