CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,本博客主要记录自己用 Python 在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。
CheckiO 官网:https://checkio.org/
我的 CheckiO 主页:https://py.checkio.org/user/TRHX/
CheckiO 题解系列专栏:https://itrhx.blog.csdn.net/category_9536424.html
CheckiO 所有题解源代码:https://github.com/TRHX/Python-CheckiO-Exercise
题目描述
【Bigger Price】:给定两个参数,第一个为整形,第二个是由字典组成的列表,要求在该列表中,按照字典中 price
关键字的值,查找前几个最大的字典,输出由最大的几个字典组成的列表。
【链接】:https://py.checkio.org/mission/bigger-price/
【输入】:两个参数,整数和字典列表,每个字典都有两个键:name
和 price
。
【输出】:由最大的几个字典组成的列表
【范例】:
bigger_price(2, [{"name": "bread", "price": 100},{"name": "wine", "price": 138},{"name": "meat", "price": 15},{"name": "water", "price": 1}
]) == [{"name": "wine", "price": 138},{"name": "bread", "price": 100}
]bigger_price(1, [{"name": "pen", "price": 5},{"name": "whiteboard", "price": 170}
]) == [{"name": "whiteboard", "price": 170}]
解题思路
利用 sorted()
方法对字典按照 price
的值进行排序,此处可以使用匿名函数 lambda
,最后按照给定的整数进行切片即可。
匿名函数参考:https://blog.csdn.net/zjuxsl/article/details/79437563
代码实现
def bigger_price(limit: int, data: list) -> list:"""TOP most expensive goods"""return sorted(data, key=lambda i: i["price"], reverse=True)[0:limit]if __name__ == '__main__':from pprint import pprintprint('Example:')pprint(bigger_price(2, [{"name": "bread", "price": 100},{"name": "wine", "price": 138},{"name": "meat", "price": 15},{"name": "water", "price": 1}]))# These "asserts" using for self-checking and not for auto-testingassert bigger_price(2, [{"name": "bread", "price": 100},{"name": "wine", "price": 138},{"name": "meat", "price": 15},{"name": "water", "price": 1}]) == [{"name": "wine", "price": 138},{"name": "bread", "price": 100}], "First"assert bigger_price(1, [{"name": "pen", "price": 5},{"name": "whiteboard", "price": 170}]) == [{"name": "whiteboard", "price": 170}], "Second"print('Done! Looks like it is fine. Go and check it')
大神解答
大神解答 NO.1
import heapqbigger_price = lambda limit, data: heapq.nlargest(limit, data, key=lambda item: item["price"])
大神解答 NO.2
bigger_price = lambda l, d: sorted(d, key=lambda e: -e["price"])[:l]