check.io 上的題目:求出 list 裡 topN 貴的物品儲存方式是dicionary,每個物品各有兩個 key 分別為 name & price
此系列文章主要是自己在解題時覺得有趣的題目,記錄下來讓自己以後好複習,有興趣的人可以參考看看
先來看看題目
看完題目可能會覺得小複雜,一般題目出有關 dictionary 的題目大多都只要找出一個最大或最小的 key 值,很直覺就會想到要用max/min的函式來解決(詳細用法在此篇文章有提到),這裡還要找不只一個,但認真想想其實也沒很難,用sort就可以一行輕鬆解決了。
sorted 的用法
語法:sorted(list, key=parameters, reverse=True/False)
基本
1 | x = [3, 2, 6, 1, 9] |
output:
1 | [1, 2, 3, 6, 9] |
反向排序(大到小)
1 | y = sorted(x, reverse=True) |
output:
1 | [9, 6, 3, 2, 1] |
進階
example 1:
1 | x = [("Amy", 150, 60), |
output:
1 | [('Wen', 145, 70), ('Amy', 150, 60), ('Emily', 154, 55)] |
example 2:
1 | x = [{"fruit": "apple", "price": 20}, |
output:
1 | [{'fruit': 'banana', 'price': 18}, {'fruit': 'apple', 'price': 20}, {'fruit': 'peach', 'price': 25}] |
解答:
1 | def bigger_price(limit: int, data: list) -> list: |