-1

i have a list L = [['92', '022'], ['77', '13'], ['82', '12']]

want to sort on second element as key : ['022','13','12']

having to custom functions for numerically sort and lexicographically sort. but not getting the desired output...

for numerically sort output like : [['82', '12'],['77', '13'],['92', '022']]

for lexicographically sort output like : [['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 Answers 2

0

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']]
Sign up to request clarification or add additional context in comments.

Comments

0

You are making it complex. key argument can take a custom 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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.