:DictとSortedDictの順/逆順でキー値タプルにアクセスするには? - 辞書を考えるとジュリア
> 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>:?
そして私はジュリアが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
は多少のようなPythonのIndexError
たときに、リストISNのインデックス」BoundsError
です見つけた?
質問の他の部分が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
また、値に基づいて辞書を並べ替える方法はありますか。
そして、最後に、ソートされたdictをどのように逆転させるのですか?
私は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
この質問は、噛むことがたくさんあります。将来、2つの質問に分割することを検討してください... –
それぞれの質問を別々にお尋ねください。また、「0」でインデックスのペアを含む試行を含めることは役に立ちません。 'BoundsError'について尋ねたいのであれば、別途行うこともできます。 –