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?
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.
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))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With