6

I have written a program which must sort the following:

unsorted_list=[['le', 5], ['aab', 4], ['aaa', 5]]

to:

[['aaa', 5], ['le', 5], ['aab', 4]]

It should be sorted by number. If the numbers are the same then it should sort alphabetical. I have the following code:

def sortItem(lista):
    ''' func for sort by item'''
    return lista[1]
sorted(unsorted_list, key=sortItem, reverse=True)

Unfortunately, it does not return string alphabetical. Any suggestion how to do it?

3 Answers 3

10

Since x[1] is an integer, you can sort it from maximum to minimum simply by negating it:

sorted(unsorted_list, key=lambda x: (-x[1], x[0]))

The tuples created in key will be sorted according to the first element (-x[1]), then by second element (x[0]). This corresponds exactly to your logic:

"So, it means than it is sorted by number but if numbers are the same the sort will be alphabetical."

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

1 Comment

And the reason this works is because sequences are compared lexicographically
6
In [2]: l = [['le', 5], ['aab', 4], ['aaa', 5]]

In [3]: sorted(l, key=lambda (x,y):(-y,x))
Out[3]: [['aaa', 5], ['le', 5], ['aab', 4]]

Comments

0

If someone is not familiar with the lambda function, here is how to break this down by defining your own function from the scratch -

unsorted_list=[['le', 5], ['aab', 4], ['aaa', 5]]
def num_and_alpha(tuple):
    return (-tuple[1], tuple[0])

print sorted(unsorted_list, key=num_and_alpha)

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.