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

时间:2020-07-04 09:39:49

标签: python sorting comparator custom-sort

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


2 个答案:

答案 0 :(得分:0)

您正在使其变得复杂。 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))

答案 1 :(得分:0)

请尝试这个-它应该可以工作:

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']]
相关问题