0

I was trying to sort list of lists in python but it doesn't seem to work.

def get(l):
        return l[1]

def com(x,y):
        return len(x) < len(y)

x = [['jis','1,2334'],['hshshau','123'],['sjuaj','3214']]
x.sort(cmp=com,key=get)

Output

[['jis', '1,2334'], ['hshshau', '123'], ['sjuaj', '3214']]

How to achieve list in increasing order of 2nd element ? Thanks.

2 Answers 2

2

You don't need cmp here just use a key :

>>> x = [['jis','1,2334'],['hshshau','123'],['sjuaj','3214']]
>>> 
>>> x.sort(key=lambda x:len(x[1]))
>>> x
[['hshshau', '123'], ['sjuaj', '3214'], ['jis', '1,2334']]
>>> 

And you need to know that sort function will sort the list elements based on the key and here your key doesn't consider the length of your elements. you just sorting based on second element and sort will sort your list based on second element lexicographicaly!

For more information about python sort function read https://docs.python.org/2/library/functions.html#sorted

Sign up to request clarification or add additional context in comments.

Comments

1

Like @Kasra said you do not need to use the cmp parameter, you can just use the key , also if you want to consider the second element as integers (numbers) you can replace',' with '' (Assuming only , will come in that) (empty string) and then convert to int and use, so that numbers of same length are also sorted correctly.

Example -

>>> x = [['jis','1,2334'],['hshshau','123'],['sjuaj','3214'],['nbhd','1,841']]
>>> x.sort(key = lambda x: int(x[1].replace(',','')))
>>> x
[['hshshau', '123'], ['nbhd', '1,841'], ['sjuaj', '3214'], ['jis', '1,2334']]

From the documentation for cmp argument -

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number

As you can see above, cmp function needs to return 0 if both are equal, positive number if the first is greater and negative number if the first is less than the second argument.

But in your case you are returning a boolean value, causing the issue.

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.