Sort by last name

How do I get a person with the first surname in the following:

l = ['John Fine', 'Doug Biro', 'Jo Ann Alfred'] --> Jo Ann Alfred 

So far I have been doing:

 sorted(l, key=itemgetter(-1))[0] 

Is this the recommended way to do this, or are there better alternatives?

+5
source share
2 answers

In fact, you sort by the last letter, and not by name, considering the last word after the space always using the separation of the last name:

 l = ['John Fine', 'Doug Biro', 'Jo Ann Alfred'] sorted(l, key=lambda x: x.rsplit(None,1)[-1]) 

If you want the name-based min value to use min :

 print(min(l,key=lambda x: x.rsplit(None,1)[-1])) 

For reverse use max .

lambda x: x.rsplit(None,1)[-1] actually splits the line at the last space and uses this value as a key for sorting.

+6
source

when you need to execute min, min not sort :

min(l, key=lambda x: x.rsplit(' ', 1)[1])

EDIT:

I think the best solution would be: 1. Compare the last name and 2. If they are equal, compare the first. we can easily achieve this behavior using tuples:

 min(l, key=lambda x:tuple(reversed(x.rsplit(None, 1)))) 
+4
source

Source: https://habr.com/ru/post/1216421/


All Articles