我有一个列表 L = [['92', '022'], ['77', '13'], ['82', '12']]
想要将第二个元素作为键进行排序:['022','13','12']
必须自定义函数以进行数字排序和字典排序。但没有得到想要的输出......
对于数字排序输出,例如: [['82', '12'],['77', '13'],['92', '022']]
用于按字典顺序排序输出,例如: [['92', '022'],['82', '12'], ['77', '13']]
from functools import cmp_to_key
L = [['92', '022'], ['77', '13'], ['82', '12']]
key=2
def compare_num(item1,item2):
return (int(item1[key-1]) > int(item2[key-1]))
def compare_lex(item1,item2):
return item1[key-1]<item2[key-1]
print(sorted(l, key=cmp_to_key(compare_num)))
print(sorted(l, key=cmp_to_key(compare_lex)))