【发布时间】:2017-06-25 11:49:15
【问题描述】:
给定一本字典:
> d = Dict{Int, Int}(1=>123, 2=>51, 4=>23)
Dict{Int64,Int64} with 3 entries:
4 => 23
2 => 51
1 => 123
我可以通过键访问字典的值,例如:
> d[4]
23
或者我可以像这样遍历键值对:
> for i in d
println(i)
end
4=>23
2=>51
1=>123
我尝试将密钥作为列表的第一个元素甚至i.key 访问,但它似乎不是正确的语法:
julia> for i in d
println(i.key)
end
ERROR: type Pair has no field key
in macro expansion; at ./REPL[22]:2 [inlined]
in anonymous at ./<missing>:?
julia> for i in d
println(i[0])
end
ERROR: BoundsError: attempt to access 4=>23
at index [0]
in getindex(::Pair{Int64,Int64}, ::Int64) at ./operators.jl:609
in macro expansion; at ./REPL[23]:2 [inlined]
in anonymous at ./<missing>:?
然后我记得 Julia 不是第 0 个索引,所以应该是:
> for i in d
println(i[1], ' ', i[2])
end
4 23
2 51
1 123
> for i in d
println(i[1], ' ', i[2])
end
4 23
2 51
1 123
在这种情况下,在找不到列表索引时,BoundsError 是否有点像 Python 的 IndexError?
问题的另一部分是关于SortedDict,如何访问SortedDict 中的最后第N 个元素?
我尝试过使用索引语法并检索到值,但没有检索到 (key,value) 的元组。
julia> import DataStructures: SortedDict
julia> sd = SortedDict(d)
DataStructures.SortedDict{Int64,Int64,Base.Order.ForwardOrdering} with 3 entries:
1 => 123
2 => 51
4 => 23
julia> sd[end]
23
另外,如何根据值对字典进行排序?
最后,如何反转排序的字典?
我尝试过使用Base.Order.ReverseOrding,但它抛出了MethodError:
julia> sd = SortedDict{Base.Order.ReverseOrdering}(d)
ERROR: MethodError: Cannot `convert` an object of type Dict{Int64,Int64} to an object of type DataStructures.SortedDict{Base.Order.ReverseOrdering,D,Ord<:Base.Order.Ordering}
This may have arisen from a call to the constructor DataStructures.SortedDict{Base.Order.ReverseOrdering,D,Ord<:Base.Order.Ordering}(...),
since type constructors fall back to convert methods.
in DataStructures.SortedDict{Base.Order.ReverseOrdering,D,Ord<:Base.Order.Ordering}(::Dict{Int64,Int64}) at ./sysimg.jl:53
【问题讨论】:
-
这个问题值得细细琢磨。以后,考虑把它分成两个问题...
-
请分别提出每个问题。此外,将尝试包含在
0的索引对中也无济于事。如果您想询问BoundsError,也可以单独进行。
标签: sorting dictionary julia key-value