1. 程式人生 > >008. Python字典排序

008. Python字典排序

Bigger price

一、題目描述

要求:有一個列表,列表的內容是字典;字典的內容是貨物:價格鍵值對,給定引數n,返回最貴的n個貨物的字典列表

輸入:字典列表和n

輸出:字典列表

示例

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}]

二、解題示例

1. lambda、排序

def bigger_price(limit: int, data: list) -> list:
    """
        TOP most expensive goods
    """
# your code here sorted_list = sorted(data, key=lambda x: x['price'])[-limit:] sorted_list.reverse() return sorted_list if __name__ == '__main__': from pprint import pprint print('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-testing assert 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')

2.精簡寫法

def bigger_price(limit, data):
    return sorted(data, key=lambda x: x['price'], reverse=True)[:limit]

if __name__ == '__main__':
    from pprint import pprint
    print('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-testing
    assert 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')