我在 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 中,是否还有任何其他方法可以使有序字典不可变?
最佳答案
根据 docs , 对于 OrderedDict
order refers to insertion order.
我不知道这怎么会“失去它的顺序”,但也许你只是在改变东西?
可能您想要的更接近 SortedDict
;但是,这是按键而不是值排序的。按值排序的字典有点不寻常。
如果你想要一个具有快速按键查找和按值排序迭代的可变数据结构,你可以通过两层方法来模拟它:一个普通的字典用于存储原始键和标记之间的映射,第二个 SortedMultiDict{ValueType, Nothing}
模拟 token 索引到的排序多重集。然后你定义自己的机制以通过 token 以某种方式进行间接查找,如下所示:
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,如果你从不打算改变事物,你可以做一个非常相似的事情,你存储一个 Dict{KeyType, Int}
和一个 Vector{ValueType}
一起 sort!
向量在开头一次。 (@mcabbot 的回答中描述的 Dictionaries.jl 基本上实现了这一点。)
关于Julia 中的排序字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70575941/