Ruby 中的散列首先按其值排序,然后按其键排序 [英] Sorting a hash in Ruby by its value first then its key
本文介绍了Ruby 中的散列首先按其值排序,然后按其键排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据单词出现的次数对文档进行排序,然后按单词的字母顺序排列,以便在输出时看起来像这样.
未分类:'的','6'我们",7"'那些','5''有','3'排序:我们",7"'的','6''那些','5''有','3'
解决方案
试试这个:
假设:
a = {'该' =>'6','我们' =>'7','那些' =>'5','有' =>'3','有' =>'3','避风港' =>'3'}
然后在这样做之后:
b = a.sort_by { |x, y|[ -Integer(y), x ] }
b
看起来像这样:
编辑为按反向频率排序.
I am trying to sort a document based on the number of times the word appears then alphabetically by the words so when it is outputted it will look something like this.
Unsorted:
'the', '6'
'we', '7'
'those', '5'
'have', '3'
Sorted:
'we', '7'
'the', '6'
'those', '5'
'have', '3'
解决方案
Try this:
Assuming:
a = {
'the' => '6',
'we' => '7',
'those' => '5',
'have' => '3',
'hav' => '3',
'haven' => '3'
}
then after doing this:
b = a.sort_by { |x, y| [ -Integer(y), x ] }
b
will look like this:
[
["we", "7"],
["the", "6"],
["those", "5"],
["hav", "3"],
["have", "3"],
["haven", "3"]
]
Edited to sort by reverse frequencies.
这篇关于Ruby 中的散列首先按其值排序,然后按其键排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文