python - Sorting integers and strings in a single line code -


so have following list represents students , grades:

a = [('tim jones', 58), ('anna smith', 64), ('barry thomas', 80), ('tim smith', 80), ('yulia smith', 66)]  

i need define function sort students grades in descending order surnames , lastly forenames. following line of code works fine:

def sortstudents(a):     return sorted(a, key=lambda x : (-x[1], x[0])) 

but need make sure works grades strings instead of integers , above function fails tests. figured " - " causing problems tried:

return (sorted(a, key=lambda x: (x[1], x[0]), reverse=true)) 

but reverses whole lists , it's not working intended, though passes string test.

what think need check if grade integer , if - execute first version of code, , if not - execute else, still haven't figured out.

anyone has ideas?

you close need turn score int , need split , reverse name:

>>> sorted(a, key=lambda x: (-int(x[1]), tuple(reversed(x[0].split())))) [('tim smith', 80),  ('barry thomas', 80),  ('yulia smith', 66),  ('anna smith', 64),  ('tim jones', 58)] 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -