Download Chapter 5

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Guide to Programming with
Python
Chapter Five
Lists and Dictionaries: The Hangman Game
Sequences so far
 Strings "", tuples ()
 General sequence functions/operators/methods
– len(seq)
– "w" in "word"
– seq[i] (indexing)
– seq[beg:end] (slicing)
– seq1 + seq2 (concatenation)
– "abc".index("a")
 for loops: iterates over a sequence
– for letter in "word":
– for idx in range(len("word")):
– while idx < len("word")
Objectives
 Lists are similar to tuples in many senses
– Create, index, and slice a list (similarly to tutle)
 Lists are mutable sequences (tuples are
immutable)
– Add and delete elements from a list
– Use list methods to append, sort, and reverse a list
 Use nested sequences to represent even more
complex information
– NumPy (http://numpy.scipy.org/)
 Use dictionaries (not ordered!) to work with pairs
of data
– Add and delete dictionary items
Guide to Programming with Python
3
Lists are Similar to Tuples
 List: A mutable (changeable) sequence of any
type
 Creating List
inventory = []
inventory = ["sword", "armor", "shield",
"healing potion"]
[]
Tuple: inventory = (“sword”, “armor”, “shield”, “healing potion”)
 Using len() function and in operator
if "healing potion" in inventory:
print "You will live to fight another day.”
 Indexing and slicing inventory[1],
GuideConcatenating
lists list1 + list2
to Programming with Python
inventory[1:3]
4
Understanding List Mutability
 Mutable: Changeable
 Lists are mutable
– Elements (or slices) can be added
– Elements (or slices) can be removed
Guide to Programming with Python
5
Assigning a New Element Or Slice
>>> inventory = ["sword", "armor", "shield",
"healing potion", "gold", "gems"]
>>> inventory[0] = "crossbow"
>>> print inventory
['crossbow', 'armor', 'shield', 'healing potion',
'gold', 'gems’]
>>> inventory[4:6] = ["orb of future telling"]
>>> print inventory
['crossbow', 'armor', 'shield', 'healing potion',
'orb of future telling']
(Replaces the two elements inventory[4] and
inventory[5] with "orb of future telling”)
Guide to Programming with Python
6
Deleting an Element or a Slice
>>> inventory = ["crossbow", "armor", "shield",
"healing potion",
"orb of future telling"]
>>> del inventory[2] Designate element to delete after del
>>> print inventory
['crossbow', 'armor', 'healing potion', 'orb of
future telling']
>>> del inventory[:2]
>>> print inventory
['healing potion', 'orb of future telling’]
Guide to Programming with Python
7
List Methods
ascending order by default
Table 5.1: Selected list methods
Guide to Programming with Python
8
When to Use Tuples Instead of Lists
 Tuples are faster than lists
 Tuples’ immutability makes them perfect for
creating constants because they can’t change
 Rule of thumb: Use lists over tuples in most cases
Guide to Programming with Python
9
Using Nested Sequences
 Nested Sequence: A sequence inside another
sequence
 A list can contain lists or tuples
 A tuple can contain tuples or lists
scores = [("Moe", 1000), ("Larry", 1500),
("Curly", 3000)]
scores[2] is the element of the list at position 2
scores[2][0] is the element at position 0 of scores[2]
multiple indexing
Guide to Programming with Python
10
Unpacking a Sequence
>>> name, score = ("Shemp", 175)
>>> print name
Shemp
>>> print score
175
 Sequence unpacking: Automatically accessing
each element of a sequence
 The tuple is unpacked as result of assignment
statement
Guide to Programming with Python
11
Accessing Elements of a Nested
Sequence
scores[1][0] multiple indexing
scores = [("Moe", 1000), ("Larry", 1500)]
for entry in scores:
score, name = entry
print name, "\t", score
Sequence unpacking: Automatically accessing each
element of a sequence as a result of assignment statement
Guide to Programming with Python
12
Variable References
 A variable refers to a place in memory where the
value (or empty) is stored
language = “Python”
language
“Python”
 Variable assignment can be
– initial (creates a new box in the computer’s memory
the first time a variable name is seen)
– shared (assign lists; default for mutable items)
• a = b = [] # both names will point to the same list
– copied (numbers, strings, tuples)
# All variables refer to same single list
Shared Reference – Changes Applied to All
Variables Sharing References
“red sweater”
mike[2] = “red sweater”
Then mr_dawson[2], and honey[2] => “red sweater”
Shared reference could cause serious problem if you are not
aware of this (see the Sodoku puzzle solver)
Guide to Programming with Python
14
Avoid Shared References
>>> mike = ["khakis", "dress shirt", "jacket"]
>>> honey = mike[:]
>>> honey[2] = "red sweater"
>>> print honey
['khakis', 'dress shirt', 'red sweater']
>>> print mike
['khakis', 'dress shirt', 'jacket’]
 List slicing can create a new copy of a list and
avoid shared references (but NOT for nested
sequences)
a = [1, 2, [3, 4]]
b = a[:]
b[1] = "22”
b[2][0] = "33"
Guide to Programming with Python
15
Using copy.deepcopy()
 Module: copy
– ref: http://docs.python.org/library/copy.html
import copy
b = copy.copy(a) #shallow copy, => b = a[:]
b = copy.deepcopy(a) #deep copy of an object
#A deep (shallow) copy constructs a new compound
object and then, recursively, inserts copies
(references) into it of the objects found in the
original.
Example: sokodu1 = copy.deepcopy(sokodu)
NumPy for Arrays of Numeric Numbers
(instead of Using Nested Sequences)
 Initialize a 2D-array
a = [[0]*3]*3
a[1][1] = 1
# It has the “shared reference problem”
 Ref: http://numpy.scipy.org/
import numpy
numpy.zeros([3,3], int)
Guide to Programming with Python
17
Using Dictionaries
 Dictionary: A mutable collection of key-value
pairs
 Like tuple and list, dictionary is another built-in type
 Unlike tuples and lists, dictionaries don’t
organize data into sequences, but pairs
 Works like actual dictionary; look up one thing to
get another
 Look up a key to get a value
 The Geek Translator Program
Guide to Programming with Python
18
Creating Dictionaries
geek = {"404" : "clueless.",
"Uninstalled" : "being fired."}
 Creates new dictionary called geek
 geek has two entries or items
 Each item is made up of a key and a value
 404 is a key of one item; use it to look up value
"clueless."
 Create dictionary by pairing values with colon,
separated by commas, surrounded by curly braces
Guide to Programming with Python
19
Using a Key to Retrieve a Value
>>> geek["404"]
'clueless.'
>>> geek["Uninstalled"]
'being fired.'




Use key as index to get value
Cannot use value as index to get key
Using non-existent key as index produces error
Dictionaries don't have position numbers – no order
Guide to Programming with Python
20
Testing for a Key with the in Operator
>>> if "Dancing Baloney" in geek:
print "I know what Dancing Baloney is."
else:
print "I have no idea what Dancing Baloney is."
I have no idea what Dancing Baloney is.
 Use the in operator to test for key
 Condition is True if key exists in dictionary, False
otherwise
 in operator can't be used to test for dictionary
values
Guide to Programming with Python
21
The Dictionary get() Method
>>> geek.get("404")
'clueless.'
>>> geek.get("Dancing Baloney")
None
>>> geek.get("Dancing Baloney", "I have no idea.")
'I have no idea.'
 Used for retrieving value based on key
 Has built-in safety net for handling non-existent key
– If key exists, returns associated value
– If key doesn’t exist, returns a default value
Guide to Programming with Python
22
Adding a Key-Value Pair
geek["Link Rot"] = "process by which web page links
become obsolete."
 Dictionaries are mutable
 Add item by assigning value to dictionary indexed
by key
 Overwrites current entry if key already exists in
dictionary
Guide to Programming with Python
23
Deleting a Key-Value Pair
del geek["404"]
 Removes key-value pair if key exists
 Generates error if key doesn’t exist
Guide to Programming with Python
24
Selected Dictionary Methods
Table 5.1: Selected dictionary methods
Guide to Programming with Python
25
Dictionary Requirements
 Keys
– Must be unique
– Must be immutable
 Values
– Can be mutable or immutable
– Don’t have to be unique
Guide to Programming with Python
26
The Hangman Game V2
Guide to Programming with Python
27
Summary
 A list is a mutable sequence of any type
 You can add or remove list elements or slices
 A nested sequence is a sequence inside another
sequence; access an element by using multiple
indexing
 Sequence unpacking is the process of
automatically accessing each element of a
sequence
 A shared reference is a reference to an object,
which has at least one other reference to it
Guide to Programming with Python
28
Summary (continued)
 A dictionary is a mutable collection of key-value
pairs
 In a dictionary, an item is a key-value pair
 In a dictionary, a key is an object used to look up
another object
 In a dictionary, a value is an object that is returned
when its corresponding key is looked up
 The in operator can be used to test if a dictionary
contains a specific key
Guide to Programming with Python
29
Summary (continued)
 A dictionary can’t contain multiple items with the
same key
 A dictionary can contain multiple items with the
same value
 Dictionary keys must be immutable
 Dictionary values can be mutable
Guide to Programming with Python
30