Python sorted()排序

  • dict 排序

    from operator import itemgetter
    
    dicts = {"key1": "1", "key2": "2", "key3": "3"}
    sorted_dict = sorted(phone_book.items(), key=itemgetter(1))
    print(dict(sorted_dict))
    # [('key1', '1'), ('key2', '2'), ('key3', '3')]
  • 多维 list 排序

    from operator import itemgetter
    lists = [["B", 3, "key1"], ["A", 2, "key2"], ["C", 1, "key3"]]
    sorted(lists, key=itemgetter(0, 1))
    # [['A', 2, 'key2'], ['B', 3, 'key1'], ['C', 1, 'key3']]
  • 包含字典的 list 排序

    from operator import itemgetter
    rows = [
    {'name': 'Jones', 'uid': 1003},
    {'name': 'Beazley', 'uid': 1002},
    {'name': 'Cleese', 'uid': 1001},
    {'name': 'Jones', 'uid': 1004}
    ]
    rows_by_uid = sorted(rows, key=itemgetter('uid'))
    print(rows_by_uid)
    # [{'uid': 1001, 'name': 'Cleese'}, {'uid': 1002, 'name': 'Beazley'}, {uid': 1003, 'name': 'Jones'}, {'uid': 1004, 'name': 'Jones'}]
  • 包含列表的 dict 根据列表元素排序

    from operator import itemgetter
    dicts = {
    "zhang3": ["B", 3, "key1"], 
    "wang2": ["A", 2, "key2"], 
    "li4": ["C", 1, "key3"], 
    "liu5": ["E", 1, "key6"], 
    "zhao6": ["D", 5, "key5"]
    }
    sorted_dict = sorted(dicts.items(), key=lambda item: operator.itemgetter(1)(item[1]))
    print(dict(sorted_dict))
    # {'li4': ['C', 1, 'key3'], 'liu5': ['E', 1, 'key6'], 'wang2': ['A', 2, 'key2'], 'zhang3': ['B', 3, 'key1'], 'zhao6': ['D', 5, 'key5']}
上一篇:为ECS Ubuntu 18.04实例配置辅助私网IP地址


下一篇:pytest使用