python 嵌套列表排序,字典排序

1,569 阅读1分钟
temp_dict = {
    "axiaoming": 16,
    "bxiaoli": 18,
    "cxiaoxue": 19,
    "dxiaolin": 20,
    "fxiaojuan": 21,
    "exiaolu": 17,
}

temp_list_test = [
    ('cxiaoxue', 19),
    ('exiaolu', 17),
    ('dxiaolin', 20),
    ('bxiaoli', 18),
    ('axiaoming', 18),
    ('fxiaojuan', 21)
]


if __name__ == "__main__":
    # 嵌套列表(多维数组)排序
    print(f"temp_list_test before = {temp_list_test}")
    temp_list_test.sort(key=lambda x: (x[1], x[0]), reverse=False)  # 按列表的第1个元素正序,第二个元素相同的按第0个元素正序
    print(f"temp_list_test after = {temp_list_test}")

    # 嵌套列表(多维数组)排序也可用于简单字典的排序,字典排序后输出一个lis,然后可根据需要将list转为需要的类型:字典或者列表等等
    # 字典按value进行排序,输出是一个列表,列表中的每一个元素是一个元组,如下:
    
    temp_list = sorted(temp_dict.items(), key=lambda item: item[1], reverse=True)  # 按字典的val倒序排列
    print(f"temp_list = {temp_list}")

    temp_list = sorted(temp_dict.items(), key=lambda item: item[0], reverse=True)  # 按字典的key倒序排列
    print(f"temp_list = {temp_list}")