Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by last name

Tags:

python

How would I get the person with the first last name in the following:

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

So far I was doing:

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

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

like image 709
David542 Avatar asked Mar 29 '15 20:03

David542


2 Answers

You are actually sorting by the last letter not the name, presuming the last word after a space is always the last name use split:

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

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

If you just want the min value based on last name use min:

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

For the reverse use max.

lambda x: x.rsplit(None,1)[-1] actually splits the string on the last whitespace and uses that value as the key to sort.

like image 55
Padraic Cunningham Avatar answered Nov 14 '22 01:11

Padraic Cunningham


when you have to min, min don't sort:

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

EDIT:

I think a better solution will be: 1. compare the last name, and 2. if they are equal, compare the first. we can achieve that behavior easily with tuples:

min(l, key=lambda x:tuple(reversed(x.rsplit(None, 1))))
like image 4
avim Avatar answered Nov 13 '22 23:11

avim