【问题标题】:Is it possible to sort a dictionary in Julia?是否可以在 Julia 中对字典进行排序?
【发布时间】:2015-07-03 03:09:11
【问题描述】:

我使用zip() like 从两个数组中创建了一个字典

list1 = [1,2,3,4,5]
list2 = [6,7,8,9,19]
dictionary1 = Dict(zip(list1,list2))

现在我想按key(list1)list2 对这本字典进行排序。有人可以告诉我一种方式或功能,如何实现吗?

【问题讨论】:

标签: sorting dictionary data-structures julia


【解决方案1】:

虽然SortedDict 在需要保持字典排序时可能很有用,但通常只需要对字典进行排序以输出,在这种情况下,可能需要以下内容:

list1 = [1,2,3,4,5]
list2 = [6,7,8,9,19]
dictionary1 = Dict(zip(list1,list2))
sort(collect(dictionary1))

... 产生:

5-element Array{(Int64,Int64),1}:
 (1,6) 
 (2,7) 
 (3,8) 
 (4,9) 
 (5,19)

我们可以通过以下方式按值排序:

sort(collect(zip(values(dictionary1),keys(dictionary1))))

... 给出:

5-element Array{(Int64,Int64),1}:
 (6,1) 
 (7,2) 
 (8,3) 
 (9,4) 
 (19,5)

【讨论】:

  • 非常感谢您的有用回答。我认为这是一种谷歌方式,对这样的数据结构进行排序。
  • @Simon,您是否知道如何解决由于 zip 自动将密钥转换为 'SubString' 而出现的错误? ERROR: MethodError: objects of type Array{SubString{String},1} are not callable Use square brackets [] for indexing an Array.
【解决方案2】:

Sort 还需要一个by 关键字,这意味着你可以这样做:

julia> sort(collect(dictionary1), by=x->x[2])
5-element Array{Tuple{Int64,Int64},1}:
 (1,6)
 (2,7)
 (3,8)
 (4,9)
 (5,19)

另请注意,DataStructures.jl 中有一个 SortedDict 维护排序顺序,还有一个 OrderedDict 维护 插入 顺序。最后,有一个拉取请求,可以直接对OrderedDicts 进行排序(但我需要完成并提交)。

【讨论】:

  • 按值排序时比我的更简洁和更好的答案。
  • :thumbs_up: SortedDictOrderedDict 之间的区别——不要混淆!
【解决方案3】:

sort 函数的 byvalue 关键字(或用于变异/就地排序的 sort!)对于按字典的值(而不是键)的顺序对字典进行排序很有用。结果将是来自OrderedCollections.jl 的 OrderedDict 类型(它也被DataStructures.jl 重新导出)。

list1 = [2,1,3,4,5]
list2 = [9,10,8,7,6]
dictionary1 = Dict(zip(list1,list2))

按值排序(即按list2):

sort(dictionary1; byvalue=true)

输出:

OrderedDict{Int64, Int64} with 5 entries:
  5 => 6
  4 => 7
  3 => 8
  2 => 9
  1 => 10

按键排序(即按list1):

sort(dictionary1)

输出:

OrderedDict{Int64, Int64} with 5 entries:
  1 => 10
  2 => 9
  3 => 8
  4 => 7
  5 => 6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多