Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list alphabetically by the second word in a string

If I have a list and I want to keep adding lines to it and sorting them alphabetically by their last name, how could this be done? Sorted only seems to rearrange them by the first letter of the string.

    line = "James Edward"   #Example line
    linesList.append("".join(line))   #Add it to a list
    linesList = sorted(linesList)   #Sort alphabetically
like image 490
user3080274 Avatar asked Nov 30 '22 19:11

user3080274


1 Answers

linesList.sort(key=lambda s: s.split()[1])

More info: https://wiki.python.org/moin/HowTo/Sorting#Key_Functions

like image 52
U2EF1 Avatar answered Dec 06 '22 10:12

U2EF1