在 python 中使用自定义比较器函数进行排序

Sorting using custom comparator function in python

我有一个列表 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)))


你把它弄复杂了。 key 参数可以采用自定义函数。

l = [['92', '022'], ['77', '13'], ['82', '12']]
key = 2

def compare_num(item1):
   return int(item1[key-1])

def compare_lex(item1):
   return item1[key-1]

print(sorted(l, key=compare_num))
print(sorted(l, key=compare_lex))

请试试这个 - 它应该有效:

L = [['92', '022'], ['77', '13'], ['82', '12']]

#Numerically sorted:
sorted(L, key = lambda x: x[-1])
[['92', '022'], ['82', '12'], ['77', '13']]

#Lexicographically sorted:
sorted(L, key = lambda x: int(x[-1]))
[['82', '12'], ['77', '13'], ['92', '022']]