按值然后按键对散列进行排序(但键是相反的) [英] Sorting a hash by value then by key (but the key is reversed)

查看:95
本文介绍了按值然后按键对散列进行排序(但键是相反的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说明了一切.

total = {"Bob"=>37, "Alice"=>42, "Carl"=>42}

我想先按值排序,然后再按键排序,但键要按降序排列.

I want to sort it by value, and then by key, but with the key in descending order.

像这样:

{"Bob"=>37, "Carl"=>42, "Alice"=>42}

我尝试过:

return total.sort_by { |k, v| [v, k] }

但是从这里我不知道如何反转k ...

But from here I don't know how to reverse k...

推荐答案

使用排序:

total = {"Bob"=>37, "Alice"=>42, "Carl"=>42}
total.sort { |(k1, v1), (k2, v2)| [v1, k2] <=> [v2, k1] }.to_h
# => {"Bob"=>37, "Carl"=>42, "Alice"=>42}

首先,按值(v1 <=> v2)排序,然后按键(k2 <=> k1)反向排序,由于我们同时需要它,因此将其放入数组中.

First, sort by values (v1 <=> v2) and then reverse sort by keys (k2 <=> k1), and since we need it simultaneously, put it into array.

@ Mirror318,它看起来很吓人,在这里查看出色的解释:

@Mirror318, it just looks scary, take a look at the excellent explanation here: What is the Ruby <=> (spaceship) operator?

这篇关于按值然后按键对散列进行排序(但键是相反的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆