哈希可以按键或值排序吗?

时间:2019-05-31 14:30:13

标签: dictionary hashtable crystal-lang

是否可以在以下代码中按键或按值对Hash进行排序:

myhash.each_key do |key| 
   print myhash[key], "\t:\t", key, "\n" 
end

2 个答案:

答案 0 :(得分:1)

由于Crystal Hash保留了插入顺序,因此实际上可以进行排序的Hash

myhash.to_a.sort.to_h

要按值排序,

myhash.to_a.sort_by { |k, v| v }.to_h

要就地排序,它有点笨重:

myhash = {5 => "five", 3 => "three", 2 => "two", 4 => "four", 1 => "one"}

entries = myhash.to_a.sort
myhash.clear
entries.each { |k, v| myhash[k] = v }

答案 1 :(得分:0)

按键排序:

Dim PT1 As PivotTable
Dim PTCache As PivotCache '<-- define new Pivot-Cahce Object

' set the Range Address as String
PTSourceRngFcst = Rng.Address(False, False, xlA1, xlExternal)

' set the Pivot Cache
Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PTSourceRngFcst)

' set The Pivot Table object
Set PT1 = ThisWorkbook.Sheets("Pivots").PivotTables("Customer_Cat_LocnType")

' refresh the Pivot Cache
PT1.ChangePivotCache PTCache
PT1.RefreshTable

产生

myhash = {5 => "five", 3 => "three", 2 => "two", 4 => "four", 1 => "one"}

myhash.keys.sort.each do |key| 
  print myhash[key], "\t:\t", key, "\n" 
end

按价值排序要花费更多的精力:

one     :   1
two     :   2
three   :   3
four    :   4
five    :   5

产生

myhash.to_a.sort { |item1, item2| item1[1] <=> item2[1] }.each do |item|
  puts item.join("\t:\t")
end

如果您希望按值:关键顺序生成结果,请更改

5   :   five
4   :   four
1   :   one
3   :   three
2   :   two

puts item.join("\t:\t")