python sorted sorts by multiple key values (including lambda and custom functions)

The sorted function can sort data according to multiple key values, and proceed sequentially according to the order in which the key values ​​are passed in. When the previous elements are the same, continue to sort according to the subsequent key values.

data = [(12, 24), (12, 15), (15, 24), (7, 30), (30, 24)]
print(sorted(data, key=lambda x:(x[0], x[1]))) #根据元祖第一个值升序排序,若第一个值相等则根据第二个值升序排序
print(sorted(data, key=lambda x:(x[0], -x[1])))#根据元祖第一个值升序排序,若第一个值相等则根据第二个值降序排序

#输出
[(7, 30), (12, 15), (12, 24), (15, 24), (30, 24)]
[(7, 30), (12, 24), (12, 15), (15, 24), (30, 24)]


#同时也可通过传入自定义函数进行排序,两者结果一致
def cmp1(x):
    return x[0], x[1]
def cmp2(x):
    return x[0], -x[1]
print(sorted(data, key=cmp1)) #根据元祖第一个值升序排序,若第一个值相等则根据第二个值升序排序
print(sorted(data, key=cmp2)) #根据元祖第一个值升序排序,若第一个值相等则根据第二个值降序排序

#输出
[(7, 30), (12, 15), (12, 24), (15, 24), (30, 24)]
[(7, 30), (12, 24), (12, 15), (15, 24), (30, 24)]

Guess you like

Origin blog.csdn.net/yangyanbao8389/article/details/121646041