【发布时间】:2019-05-31 14:30:12
【问题描述】:
是否可以在以下代码中按键或按值对Hash 进行排序:
myhash.each_key do |key|
print myhash[key], "\t:\t", key, "\n"
end
【问题讨论】:
标签: dictionary hashtable crystal-lang
是否可以在以下代码中按键或按值对Hash 进行排序:
myhash.each_key do |key|
print myhash[key], "\t:\t", key, "\n"
end
【问题讨论】:
标签: dictionary hashtable crystal-lang
按键排序:
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
如果你想要 value:key order 中的结果,请更改
puts item.join("\t:\t")
到
puts item.reverse.join("\t:\t")
【讨论】:
由于 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 }
【讨论】: