Created
October 3, 2012 00:17
-
-
Save dancollins/3824166 to your computer and use it in GitHub Desktop.
Sort names by reversed first name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Given a list of names, this program will sort them by the last letter of their first name. | |
It does this by reversing their first name, and sorting a dictionary like that. | |
Dan Collins 2012 | |
''' | |
import operator | |
names = ['Andrew Hornblow', 'Bobby', 'Bruce Lee', 'Dan Collins', 'Fabian Cook', 'Matthew', 'Ross Petersen'] # Names to sort | |
namesWithSort = {} # This will be a dictionary where key: value = name: reversedFirstName | |
for name in names: | |
splitName = name.split(' ') # Split each name into first and last name | |
namesWithSort[name] = splitName[0][::-1] # Reverse the first name | |
sortedNamesDict = sorted(namesWithSort.iteritems(), key=operator.itemgetter(1)) # This sorts the dictionary based on the reversed first name alphabetically | |
outputList = [] # Will save the sorted names to here | |
for kvp in sortedNamesDict: # Loop over all the keys+values in the dictionary | |
outputList.append(kvp[0]) # Add the fullname to the output list | |
print outputList # Display the result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment