简体   繁体   English

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

[英]Sorting using custom comparator function in python

i have a list L = [['92', '022'], ['77', '13'], ['82', '12']]我有一个列表 L = [['92', '022'], ['77', '13'], ['82', '12']]

want to sort on second element as key: ['022','13','12']想要将第二个元素作为键进行排序:['022','13','12']

having to custom functions for numerically sort and lexicographically sort.必须自定义函数以进行数字排序和字典排序。 but not getting the desired output...但没有得到想要的 output...

for numerically sort output like: [['82', '12'],['77', '13'],['92', '022']]用于对 output 进行数字排序,例如: [['82', '12'],['77', '13'],['92', '022']]

for lexicographically sort output like: [['92', '022'],['82', '12'], ['77', '13']]用于按字典顺序对 output 进行排序,例如: [['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)))


You are making it complex.你让它变得复杂。 key argument can take a custom function. key参数可以采用自定义 function。

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))

Please try this - it should work:请试试这个 - 它应该工作:

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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM