# Given scores of N athletes, find their relative ranks and the people with the top three highest scores, # who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal". # Input: [5, 4, 3, 2, 1] # Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] # Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". # For the left two athletes, you just need to output their relative ranks according to their scores. # 题意是输入一个列表,列表中的是运动员的得分, 我们根据得分为每一个人发奖牌, 得分最高的前三名分别获得金银铜牌, # 剩下的运动员输出他们拍第几名(4, 5, 6...), 输出仍然按照输入的排列顺序输出 # 基本思路如下: # 1 先将分数排序,也就是nums由大到小排序 # 2 生成新的列表,包括金银铜牌, 以及剩余运动员的排名, [金, 银, 铜, 4(第四名), 5(第五名), 6(第六名)] # 需要注意的是map之后是一个函数,转换成list时需要加上list(map(...)) # 3 利用zip函数生成由元祖组成的列表, zip函数,http://www.runoob.com/python/python-func-zip.html # zip(iterable, iterable2) 由iterable中的对应数据组成元祖,多个元组组成列表 # [(7, 'Gold Medal'),(6, 'Silver Medal'),(5, 'Bronze Medal'),(4, '4'),(3, '5'),(1, '6')] # 然后生成字典,目的是为了下一步的查询 {1: '6', 3: '5', 4: '4', 5: 'Bronze Medal', 6: 'Silver Medal', 7: 'Gold Medal'} # map(dict(zip(sort, rank)).get, nums), map中第一个参数为一个函数, nums为传入函数中的参数. dict.get是获得字典中对应 # key的value值, nums中的每一个值就是传入get()中的key, 按照key的顺序查找保存至map中,并转换成list输出. # 字典用法 http://www.runoob.com/python/att-dictionary-get.html # #greg 20170516 class Soulution(object): def findRelativeRanks(self, nums): sort = sorted(nums)[::-1] rank = ['Gold Medal', 'Silver Medal', 'Bronze Medal'] + list(map(str, range(4, len(nums) + 1))) return list(map(dict(zip(sort, rank)).get, nums)) if __name__ == '__main__': nums = [7, 3, 9, 2, 5, 8] s = Soulution() print(s.findRelativeRanks(nums))
结果: