ruby - 有没有办法通过 sort / sort_by 更改哈希的键?
问题描述
目前正在解决一个试图让我将前者转变为后者的问题
{ a: 2, b: 5, c: 1 } => { a: 1, b: 2, c: 5 }
试图做到这一点
hash = { a: 2, b: 5, c: 1 }.sort_by {|k,v| v}.to_h
这给出了这个 =>{:c=>1, :a=>2, :b=>5}
如何在对值进行排序时更改哈希的键?
解决方案
看起来您正在尝试将散列拆分为键和值,分别对它们进行排序,然后将它们作为散列重新组合在一起。
在这种情况下,您可以执行以下操作:
hash.to_a.transpose.map(&:sort).transpose.to_h
一步一步,它的工作原理是这样的:
# First array-ify the hash into key/value pairs
hash.to_a
# [[:a, 2], [:b, 5], [:c, 1]]
# Then transpose to group the keys and values together
hash.to_a.transpose
# [[:a, :b, :c], [2, 5, 1]]
# Then sort the keys and values separately
hash.to_a.transpose.map(&:sort)
# [[:a, :b, :c], [1, 2, 5]]
# And transpose again to get key/value pairs
hash.to_a.transpose.map(&:sort).transpose
# [[:a, 1], [:b, 2], [:c, 5]]
# And combine the array of key/value pairs into a hash
hash.to_a.transpose.map(&:sort).transpose.to_h
# {:a=>1, :b=>2, :c=>5}
您也可以手动执行如下hash.to_a.transpose
步骤:
[hash.keys, hash.values].map(&:sort).transpose.to_h
您甚至不必假设#keys
并且#values
会以任何特定顺序生成数组,因为无论如何您都在对所有内容进行排序。
推荐阅读
- https - 通过 http 或 https 进行 PAT?
- makefile - gnu 在包含路径的参数中生成 findstring
- python - 为什么我不能为这个阶乘得到这条蟒蛇
- python - 在 Django 中隐藏当前用户未创建的条目的更好方法?
- python - 无法在python的csv文件中保存记录
- python - 如何使用 prometheus 监控 kube cron 作业?
- wordpress - Wordpress 下拉菜单仅在一页上
- python - 无法访问 Gerrit API
- python - 我可以更改 django 限速器超时吗?
- javascript - 如何通过 Jquery 将数据发送到自定义元素设置方法?