按数字(从大到小)然后按字母(字母顺序)对一组对象进行排序 [英] Sort a collection of objects by number (highest first) then by letter (alphabetical)

查看:40
本文介绍了按数字(从大到小)然后按字母(字母顺序)对一组对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个小部件来显示奥运会的奖牌数.我有一个国家"对象的集合,其中每个对象都有一个名称"属性,以及奖牌数的金"、银"、铜".

I'm building a widget to show medal counts for the Olympics. I have a collection of "country" objects, where each has a "name" attribute, and "gold", "silver", "bronze" for medal counts.

列表应该排序:1. 首先是奖牌总数2.如果奖牌相同,则按类型分次排序(金>银>铜,即两金>1金+1银)3.如果奖牌和类型相同,按字母顺序排序

List should be sorted: 1. First by total medal count 2. If same medals, sub-sort by type (gold > silver > bronze, ie. two golds > 1 gold + 1 silver) 3. If same medals and type, sub-sort alphabetically

我是用 ruby​​ 做这件事的,但我想语言无关紧要.我确实想出了一个解决方案,但如果感觉必须有一种更优雅的方法来做到这一点.

I'm doing this in ruby, but I suppose the language doesn't matter. I did figure out a solution, but if feels like there must be a much more elegant way to do it.

这是我所做的:

  1. 创建一个带有加权奖牌总数的虚拟属性.因此,如果他们有 2 枚金和 1 枚银,则加权总数将为3.020100".1金1银1铜为3.010101"

  1. Create a virtual attribute with the weighted medal total. So if they had 2 gold and 1 silver, weighted total would be "3.020100". 1 gold and 1 silver and 1 bronze would be "3.010101"

由于我们要先将奖牌数排序为最高,因此列表按 DESC 排序.但是我们想在这之后按字母顺序(即 ASC)进行子排序.所以我创建了一个函数来转换一个单词(即canada"=>xzmzwz")

Since we want to sort the medal count as highest first, list is sorted DESC. But then we want to sub-sort alphabetically (ie. ASC) after that. So I created a function which would alpha-invert a word (ie. "canada" => "xzmzwz")

将加权总数转换为字符串,连接反向名称(即3010101xzmzwz"),然后降序排序.瞧.

Convert the weighted total to a string, concat the reversed name (ie. "3010101xzmzwz"), then sort descending. Voila.

到现在为止,有人已经想出了如何用大约 2 行代码来做同样的事情.想开导我吗?

By now, someone has figured out how to do the same thing in about 2 lines of code. Care to enlighten me?

推荐答案

countries.sort_by do |country|
  medals = country.gold + country.silver + country.bronze
  [-medals, -country.gold, -country.silver, country.name]
end

这篇关于按数字(从大到小)然后按字母(字母顺序)对一组对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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