210 likes | 365 Views
Topics in Python Lists & Dictionaries. Professor Frank J. Rinaldo Creation Core - office 401. Review Slicing Strings. # create a jumbled version of the word jumble ="" while word: position = random.randrange(len(word)) jumble += word[position]
E N D
Topics in PythonLists & Dictionaries Professor Frank J. Rinaldo Creation Core - office 401
ReviewSlicing Strings # create a jumbled version of the word jumble ="" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):]
Tuples vs. ListsExample • Tuple inventory = (“sword”, “armor”, “shield”, “healing potion”) • List Inventory = [“sword”, “armor”, “shield”, “healing potion”]
Tuples vs ListsCharacteristics • Tuple • Sequence of data (can be mixed data) • Immutable • Tuples can NOT be changed • Can delete, add, but not replace • Lists • Sequence of data (can be mixed data) • Mutable • CAN be changed!
Hero’s Inventory # Hero's Inventory # create a list with some items and display with a for loop inventory = ["sword", "armor", "shield", "healing potion"] print "Your items:" for item in inventory: print item raw_input("\nPress the enter key to continue.") # get the length of a list print "You have", len(inventory), "items in your possession." raw_input("\nPress the enter key to continue.") # test for membership with in if "healing potion" in inventory: print "You will live to fight another day." # display one item through an index index = int(raw_input("\nEnter the index number for an item in inventory: ")) print "At index", index, "is", inventory[index] # display a slice begin = int(raw_input("\nEnter the index number to begin a slice: ")) end = int(raw_input("Enter the index number to end the slice: ")) print "inventory[", begin, ":", end, "]\t\t", print inventory[begin:end] raw_input("\nPress the enter key to continue.")
Hero’s InventoryContinued # concatinate two lists chest = ["gold", "gems"] print "You find a chest which contains:" print chest print "You add the contents of the chest to your inventory." inventory += chest print "Your inventory is now:" print inventory raw_input("\nPress the enter key to continue.") # assign by index print "You trade your sword for a crossbow." inventory[0] = "crossbow" print "Your inventory is now:" print inventory raw_input("\nPress the enter key to continue.")
Hero’s InventoryContinued # assign by slice print "You use your gold and gems to buy an orb of future telling." inventory[4:6] = ["orb of future telling"] print "Your inventory is now:" print inventory raw_input("\nPress the enter key to continue.") # delete an element print "In a great battle, your shield is destroyed." del inventory[2] print "Your inventory is now:" print inventory raw_input("\nPress the enter key to continue.") # delete a slice print "Your crossbow and armor are stolen by thieves." del inventory[:2] print "Your inventory is now:" print inventory raw_input("\n\nPress the enter key to exit.")
List Methods • append(value) – Adds ‘value’ to end of list • sort() – sorts a list • reverse() – reverses the order of a list • count(value) – returns the number of occurrences of ‘value’ • index(value) – returns the first position number where ‘value’ occurs • insert(j,value) – inserts ‘value’ at position j • pop([j]) – returns ‘value’ at position j & removes it from the list • pop([]) – returns last ‘value’ & removes it • remove(value) – removes first occurrence of ‘value’ from the list
When to use tuples vs lists • Tuples are faster than lists • Tuples can not change so stored more efficiently • Tuples are immutable • Can be used to create ‘constants’ • Lists are more flexible • In most cases we will use ‘lists’!
High Scoreusing Lists # High Scores # Demonstrates list methods scores = [] choice = None while choice != "0": print \ """ High Scores Keeper 0 - Exit 1 - Show Scores 2 - Add a Score 3 - Delete a Score 4 - Sort Scores """ choice = raw_input("Choice: ") print # exit if choice == "0": print "Good-bye." # list high-score table elif choice == "1": print "High Scores" for score in scores: print score
High Scoreusing Lists (continued) # add a score elif choice == "2": score = int(raw_input("What score did you get?: ")) scores.append(score) # delete a score elif choice == "3": score = int(raw_input("Delete which score?: ")) if score in scores: scores.remove(score) else: print score, "isn't in the high scores list." # sort scores elif choice == "4": scores.sort() scores.reverse() # want the highest number first # some unknown choice else: print "Sorry, but", choice, "isn't a valid choice." raw_input("\n\nPress the enter key to exit.")
Immutable vs. Mutable • Example of immutable items: • x = 10 • y = ‘string’ • z = (‘shirt’, ‘tie’, ‘pants’) • Example of mutable items (lists): • mike = [‘shirt’, ‘tie’, ‘pants’] • smith = mike • smith[2] = ‘shoes’ • print mike [‘shirt’, ‘tie’, ‘shoes’] • NOTE: variables ‘mike’ and ‘smith’ refer to SAME data!!!
Dictionaries • Data stored in pairs • It is ‘like’ a REAL dictionary • You have a entry (‘word’) • You have a value (‘definition’) • In Python • The ‘word’ is called a ‘key’ • The ‘definition’ is called a ‘value’ • Example: Dict = {“Linux” : “Unix like operating system”, “Windows” : “Microsoft operating system”}
Geek Translator # Geek Translator # Demonstrates using dictionaries geek = {"404": "clueless. From the web error message 404, meaning page not found.", "Googling": "searching the Internet for background information on a person.", "Keyboard Plaque" : "the collection of debris found in computer keyboards.", "Link Rot" : "the process by which web page links become obsolete.", "Percussive Maintenance" : "the act of striking an electronic device to make it work.", "Uninstalled" : "being fired. Especially popular during the dot-bomb era."} choice = None while choice != "0": print \ """ Geek Translator 0 - Quit 1 - Look Up a Geek Term 2 - Add a Geek Term 3 - Redefine a Geek Term 4 - Delete a Geek Term """ choice = raw_input("Choice: ") print
Geek Translator (continued) # exit if choice == "0": print "Good-bye." # get a definition elif choice == "1": term = raw_input("What term do you want me to translate?: ") if term in geek: definition = geek[term] print "\n", term, "means", definition else: print "\nSorry, I don't know", term # add a term-definition pair elif choice == "2": term = raw_input("What term do you want me to add?: ") if term not in geek: definition = raw_input("\nWhat's the definition?: ") geek[term] = definition print "\n", term, "has been added." else: print "\nThat term already exists! Try redefining it." else: print "\nThat term doesn't exist! Try adding it."
Geek Translator (continued) # redefine an existing term elif choice == "3": term = raw_input("What term do you want me to redefine?: ") if term in geek: definition = raw_input("What's the new definition?: ") geek[term] = definition print "\n", term, "has been redefined.“ # delete a term-definition pair elif choice == "4": term = raw_input("What term do you want me to delete?: ") if term in geek: del geek[term] print "\nOkay, I deleted", term else: print "\nI can't do that!", term, "doesn't exist in the dictionary." # some unknown choice else: print "\nSorry, but", choice, "isn't a valid choice." raw_input("\n\nPress the enter key to exit.")
Dictionary Methods • has_key(key) – returns TRUE if ‘key’ is in the dictionary, otherwise FALSE • get(key,[default]) – Return the ‘value’ of index ‘key’, if ‘key’ does not exist, then ‘default’ is returned • keys() – returns a list of all the keys in a dictionary • values() – returns a list of all the values in a dictionary • items() – returns a list of all items in a dictionary (‘keys’ and ‘values’)
In ClassAssignment • Create a program that prints a list of words in random order. • Use the ‘list’ data type • Print out all the words, but • Do NOT print out duplicate words
Homework • Due week 5 • Write a Python Program: • See problem #2 on page 157 of textbook. • In other words, write the ‘Character Creator’ program using a ‘dictionary’ data structure. • Include: • Simple Specification Document • Simple Pseudocode • Python code • Demonstrate program in class