Selected Sort of Names

Ene Uran 0 Tallied Votes 480 Views Share

Let's say you had a list of full names, where the name would consist of a title, followed by first, middle and last name, or maybe just title and last name. You can sort this list by last name only, by creating a temporary list of sublists of type [last name, full name].

Python makes all of this relatively easy. The last name element is obtained by splitting the full name into a list and using the last element of that list. When the temporary list of sublists is sorted, it is sorted by the first element in the sublist. Once the sort is done, simply recreate a list of the sublists' second element, removing the temporary last name item. I hope, I added enough comments in the code, so you can follow the logic.

# sort a list of names by last name

def sort_names(names):
    """
    sort names by last name, avoiding title, first and middle names
    """
    names_mod = []
    for name in names:
        # split each name into a list
        name_list = name.split()
        # pick the last name from list
        last_name = name_list[-1]
        # create a list of temporary sublists [last_name, name] 
        names_mod.append([last_name, name])
    # sort the modified list of names inplace
    # this will sort by the first item in the 
    # sublists which is last_name
    names_mod.sort()
    # use list comprehension to
    # to remove the temporary last_name item
    return [name[1] for name in names_mod]

names = [
"Dr. Heidi Karin Hirsch",
"Miss Arlene Auerbach",
"Mr. and Mrs. Larry Zoom",
"Mr. Frank Paul Lummer",
"Vicepresident Colter"
]

print "Original list of names:"
for name in names:
    print name

print
print "List of names sorted by last name:"
names_sorted = sort_names(names)
for name in names_sorted:
    print name

"""
output -->
Original list of names:
Dr. Heidi Karin Hirsch
Miss Arlene Auerbach
Mr. and Mrs. Larry Zoom
Mr. Frank Paul Lummer
Vicepresident Colter

List of names sorted by last name:
Miss Arlene Auerbach
Vicepresident Colter
Dr. Heidi Karin Hirsch
Mr. Frank Paul Lummer
Mr. and Mrs. Larry Zoom
"""