Reputation: 335
I have a list that looks like this:
['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']
The numbers represent student test scores. I want to use the sorted() function to sort the list out in student ranking, and tie breakers are names in alphabetical order. I am not too familiar with this function, so your help would be greatly appreciated! =)
Upvotes: 0
Views: 520
Reputation: 142206
Starting with:
L = ['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']
To sort by multiple keys, first, sort on the "secondary" key in the order you wish it to be, eg, we'll put it in alphabetical order ignoring case:
L.sort(key=str.lower)
Gives us:
['Claudia Zingaro,50', 'Cristi Authement,47', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,46', 'Invalid Name,48', 'Ivan Connolly,50', 'Jeffie Honaker,50', 'Yadira Millwood,47']
Then, we sort in descending order the score field:
L.sort(key=lambda L: int(L.rpartition(',')[2]), reverse=True)
That gives L
a final result of:
['Claudia Zingaro,50', 'Ivan Connolly,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']
Upvotes: 0
Reputation: 60004
Use the key
parameter with sorted()
, and adding your own function.
>>> L = ['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']
>>> def mysort(x):
... temp = x.split(',')
... return (-int(temp[1]), temp[0])
...
>>> sorted(L, key=mysort)
['Claudia Zingaro,50', 'Ivan Connolly,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']
The function is called with each value in the list. The function will return something like [46, 'Invalid Name']
. Then, sorted()
sees this and sorts it based on the list given, the first item having more priority.
Upvotes: 1
Reputation:
You can use sort(key=...)
function.
Try this:
L = ['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']
L.sort(key=lambda x:int(x.split(',')[1]))
Output:
['Invalid Name,46', 'Cristi Authement,47', 'Yadira Millwood,47', 'Hyun Castleberry,48', 'Invalid Name,48', 'Floria Rozar,49', 'Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50']
It is simple and clear.
Upvotes: 1