![](/img/trans.png)
[英]sort an array in ascending and descending order by the hash keys of the containing elements in Ruby
[英]Sort a hash by value in descending order and then key in ascending order ruby
我有這樣的哈希
trial_hash ={"key1"=>1000, "key2"=>34, "key3"=>500, "key4"=>500, "key5"=>500, "key6"=>500}
我按照值的降序排序:
my_hash = trial_hash.sort_by{|k, v| v}.reverse
我現在這樣做了:
[["key1", 1000], ["key4", 500], ["key5", 500], ["key6", 500], ["key3", 500], ["key2", 34]]
但我希望它在值相同時按鍵的升序排序。 我該怎么做?
例如:以上哈希將以這種方式排序:
[["key1", 1000], ["key3", 500], ["key4", 500], ["key5", 500], ["key6", 500], ["key2", 34]]
在比較中,數組首先通過它們的第一個元素進行評估,然后通過它們的第二個元素等進行評估。您可以使用此事實來枚舉順序比較。 比較[-v, k]
首先按值(按相反順序)排序,然后按鍵排序。
>> trial_hash.sort_by{|k, v| [-v, k]}
=> [["key1", 1000], ["key3", 500], ["key4", 500], ["key5", 500], ["key6", 500], ["key2", 34]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.