Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # In-memory Database Index Sort Demo program
- # Written on 05/13/2014 by Darryl Medley for Coding 101 on the TWiT network
- # Generic String List print routine
- def printList(nmList):
- for rec in nmList:
- print ','.join(rec) # ','.join converts each sub-list into a comma-delimited string
- # Begin main program
- print "Coding 101 In-memory Database Index Sort Demo Program\n"
- fname = "./name_list.txt"
- try:
- # hard-coded version of what is normally read from a file
- infoList = ["padre, 30, 90000","Shannon, 21, 93000","Darryl, 50, 93000","Timmy, 9, 92000"]
- # Activate this code to read the list from the name_list.txt file used for the ReadSortWrite.py program
- ## with open(fname, "r") as nameListFile: # open the text file to read
- ## # Read the file into a Python list. Each line in the file becomes a
- ## # string element in the list. .splitlines() removes the \n (newline)
- ## # character from the end of each line and filter(lamda...) skips blank lines
- ## infoList = filter(lambda r : r != '',nameListFile.read().splitlines())
- except:
- print "Error: File",fname,"does not exist"
- else:
- # Convert each comma-delimited string in the list into a sub-list
- # and remove any leading and trailing blanks (whitespace)
- infoList = [[fld.strip() for fld in s.split(",")] for s in infoList]
- # Create index lists for each field we want to sort by. Each index list is a list of
- # two-element sub-lists where the first element is the field we are sorting by (the "key")
- # and the second element is the index # of the entry in main list the key is from.
- #
- # Make the Name index upper case so it case-insensitive
- nameIdxLst = sorted([[fld[0].upper(), i] for i, fld in enumerate(infoList)])
- # Convert the Age to a number so values like 9 sort less than 10
- ageIdxLst = sorted([[int(fld[1]), i] for i, fld in enumerate(infoList)])
- # Since Zipcodes are so common we append the name to the key to subsort by name
- zipIdxLst = sorted([[fld[2]+fld[0], i] for i, fld in enumerate(infoList)])
- print "Unsorted List (Name, Age, Zipcode):"
- printList(infoList) # call our list print function defined above
- # Print the main list sorted 3 different ways side-by-side using our index lists
- print "\nSorted Lists:\n"
- print "{:20}{:20}{:20}".format("By Name:","By Age:","By Zipcode:")
- for i in range(len(infoList)):
- print "{:20}{:20}{:20}".format(','.join(infoList[nameIdxLst[i][1]]),
- ','.join(infoList[ageIdxLst[i][1]]),
- ','.join(infoList[zipIdxLst[i][1]]))
- raw_input("\n(press Enter to close)")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement