Python 复杂数据排序

goallin / 2023-08-11 / 原文

Python 复杂数据排序

通过自定义函数作为 sort 的 key 来排序复杂数据

def by_urgency(task):
    return task['urgency']


def test_sort_complicated():
    tasks = [
        {'title': 'Laundry', 'desc': 'Wash clothes', 'urgency': 3},
        {'title': 'Homework', 'desc': 'Physics + Math', 'urgency': 5},
        {'title': 'Museum', 'desc': 'Egyptian things', 'urgency': 2}
    ]
    tasks.sort(key=by_urgency)
    assert tasks[0]["urgency"] == 2 and tasks[2]["urgency"] == 5