我在 Julia 中有一本字典,我想按值排序。我找到了幾種方法來做到這一點。例如
dict = Dict(i => sqrt(i*rand()) for i = 1:20)
dict= sort(dict;byvalue = true) # method 1
dict = OrderedDict(i => sqrt(i*rand()) for i = 1:20) #method 2 using ordereddict package [https://github.com/JuliaCollections/DataStructures.j][1]
# I don't want to use collect() method as I do not want the tuples of dictionary.
但是,有時這兩種方法在從函式傳遞到函式時確實會丟失它們的順序。有沒有其他方法可以使 Julia 中的有序字典不可變?
uj5u.com熱心網友回復:
根據檔案,對于OrderedDict
order 是指插入順序。
我不知道這怎么會“失去順序”,但也許你只是在改變東西?
可能你想要的更接近于SortedDict; 但是,這是按鍵而不是值排序的。按值排序的字典是一個不尋常的應用程式。
如果您想要一個具有按鍵快速查找和按值排序的迭代的可變資料結構,您可以通過兩級方法來模擬它:一個普通的 dict 用于存盤原始鍵和標記之間的映射,第二個SortedMultiDict{ValueType, Nothing}用于模擬已排序的多集令牌索引到其中。然后你定義你自己的通過令牌間接查找的機制,就像這樣:
function insert!(d::ValueSortedDict, k, v)
_, token = insert!(d.values, v, nothing)
d.keys[k] = token
end
getindex(d::ValueSortedDict, k) = deref_key((d.values, d.keys[k]))
并相應地用于其他 get/set 樣式函式。(我沒有測驗這個,它只是閱讀檔案。)
OTOH,如果您從不打算改變事物,您可以做一個非常相似的事情,將 aDict{KeyType, Int}和 a存盤Vector{ValueType}在一起,并sort!在開始時將向量存盤一次。(在@mcabbot 的回答中描述的 Dictionaries.jl 基本上是在實作這一點。)
uj5u.com熱心網友回復:
您可能對 Dictionaries.jl 感興趣:
julia> dict = Dict(i => (i/10 rand(1:99)) for i = 1:7)
Dict{Int64, Float64} with 7 entries:
5 => 16.5
4 => 23.4
6 => 98.6
7 => 56.7
2 => 7.2
3 => 58.3
1 => 85.1
julia> using Dictionaries
julia> sort(Dictionary(dict))
7-element Dictionary{Int64, Float64}
2 │ 7.2
5 │ 16.5
4 │ 23.4
7 │ 56.7
3 │ 58.3
1 │ 85.1
6 │ 98.6
julia> map(sqrt, ans)
7-element Dictionary{Int64, Float64}
2 │ 2.6832815729997477
5 │ 4.06201920231798
4 │ 4.8373546489791295
7 │ 7.52994023880668
3 │ 7.635443667528429
1 │ 9.22496612459905
6 │ 9.929753269845127
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404581.html
標籤:
