主要是sorted对list(包含元素值是tuple)、字典排序,因为sorted是内置函数,所以不需要导入包
if __name__ == "__main__": a = [5, 7, 6, 3, 4, 1, 2] b = sorted(a) # [5, 7, 6, 3, 4, 1, 2] a = [('a', 5), ('a', 2), ('c', 3), ('d', 4)] b = sorted(a, key=lambda x: (x[0], x[1])) # 先按x[0]排序,而后再按x[1]排序, [('a', 2), ('a', 5), ('c', 3), ('d', 4)] b = sorted(a, key=lambda x: (x[0], x[1]), reverse=True) # 逆序[('d', 4), ('c', 3), ('a', 5), ('a', 2)] dic = {"ok": 3, "no": 2, "lizi": 10, "A": 13} res = sorted(dic.items(), key=lambda d: d[0]) # 返回的是list,每个值是tuple, [('A', 13), ('lizi', 10), ('no', 2), ('ok', 3)] res = sorted(dic.items(), key=lambda d: d[1]) # [('no', 2), ('ok', 3), ('lizi', 10), ('A', 13)]