Julia:Dict的用法以及一些dict的常用函式
阿新 • • 發佈:2018-11-06
function printsum(a) println(summary(a), ": ", repr(a)) end # dicts can be initialised directly: a1 = Dict(1=>"one", 2=>"two") printsum(a1) #> Dict{Int64,String} with 2 entries: Dict(2=>"two",1=>"one") # then added to a1[3] = "three" printsum(a1) #> Dict{Int64,String} with 3 entries: Dict(2=>"two",3=>"three",1=>"one") # dicts不會保持原來的順序 # dicts may alose be created with the type explicitly set a2 = Dict{Int64, AbstractString}() a2[0] = "zero" printsum(a2) # Dict{Int64,AbstractString} with 1 entry: # Dict{Int64,AbstractString}(Pair{Int64,AbstractString}(0, "zero")) # dicts, like arrays, may also be created from comprehensions a3 = Dict([i => @sprintf("%d", i) for i = 1:10]) printsum(a3) #> Dict{Any,Any}: {5=>"5",4=>"4",6=>"6",7=>"7",2=>"2",10=>"10",9=>"9",8=>"8",3=>"3",1=>"1"} # 這裡簡要介紹haskey的用法 myDict = Dict('a'=>2, 'b'=>3) println(haskey(myDict, 'a')) # true println(haskey(myDict, 'b')) # true println(haskey(myDict, 'c')) # false println('a' in keys(myDict)) # true println(values(myDict)) # [3, 2] printsum(collect(values(myDict))) # 2-element Array{Int64,1}: [3, 2] a = collect(values(myDict)) printsum(a)