-1

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


4

2 回答 2

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))
于 2020-07-04T09:49:22.037 回答
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']]
于 2020-07-04T09:54:45.170 回答