Exercises 38
代码
ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there are not 10 things in that list. Let's fix that." stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print "Adding: ", next_one stuff.append(next_one) print "There are %d items now." % len(stuff) print "There we go: ", stuff print "Let's do some things with stuff." print stuff[1] print stuff[-1] # whoa! fancy print stuff.pop() print ' '.join(stuff) # what? cool! print '#'.join(stuff[3:5]) # super stellar!
输出
Notes:
①split()函数、join()函数的应用
②列表的切片操作
Exercise 39
代码
# create a mapping of state to abbreviation states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } # create a basic set of states and some cities in them cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville' } # add some more cities cities['NY'] = 'New York' cities['OR'] = 'Portland' # print out some cities print "-" * 10 print "NY State has: ", cities['NY'] print "OR State has: ", cities['OR'] # print some states print "-" * 10 print "Michigan's abbreviation is: ", states['Michigan'] print "Florida's abbreviation is: ", states['Florida'] # do it by using the state then cities dict print "-" * 10 print "Michigan has: ", cities[states['Michigan']] print "Florida has: ", cities[states['Florida']] # print every state abbreviation print '-' * 10 for state, abbrev in states.items(): print "%s is abbreviated %s" % (state, abbrev) # print every city in state print "-" * 10 for abbrev, city in cities.items(): print "%s has the city %s" % (abbrev, city) # now do both at the same time print "-" * 10 for state, abbrev in states.items(): print "%s state is abbreviated %s and has city %s" %( state, abbrev, cities[abbrev]) print "-" * 10 # safety get a abbreviation by state that might not be there state = states.get('Texas') if not state: print "Sorrt, no Texas." # get a city with a default value city = cities.get('TX', 'Does Not Exist') print "The city for the state 'TX' is: %s" % city
输出
hashmap.py 字典的原理解读
def new(num_buckets=256): '''Initializes a Map with the given numbers of buckets.''' aMap = [] for i in range(0, num_buckets): aMap.append([]) return aMap def hash_key(aMap,key): '''Given a key this will create a number and then convert it to an index for the aMap's buckets.''' return hash(key) % len(aMap) def get_bucket(aMap, key): '''Given a key, find the bucket where it would go.''' bucket_id = hash_key(aMap, key) return aMap[bucket_id] def get_slot(aMap, key, default=None): ''' Returns the index, key, and value of a slot found in a bucket. Returns -1, key, and default (None if not set) when not foune. ''' bucket = get_bucket(aMap, key) for i, kv in enumerate(bucket): k, v = kv if key == k: return i, k, v return -1, key, default def get(aMap, key, default=None): '''Gets the value in a bucket for the given key, or the default''' i, k, v = get_slot(aMap, key, default = default) return v def set(aMap, key, value): '''Sets the key to the Value, replacing any existing value.''' bucket = get_bucket(aMap. key) i, k, v = get_slot(aMap, key) if i >= 0: # the key exits, replace it bucket[i] = (key, value) else: # the key does not, append to create it. bucket.append(key,value) def delete(aMap, key): '''Deletes the given key from the Map.''' bucket = get_bucket(aMap, key) for i in xrange(len(bucket)): k, v = bucket[i] if key == k: del bucket[i] break def list(aMap): '''Prints out what's in the Map.''' for bucket in aMap: if bucket: for k, v in bucket: print k, v
附加代码/小实验 ex39_test.py
import hashmap # create a mapping of state to abbreviation states = hashmap.new() hashmap.set(states, 'Oregon', 'OR') hashmap.set(states, "Florida", 'FL') hashmap.set(states, 'California', 'CA') hashmap.set(states, 'New York', 'NY') hashmap.set(states, 'Michigan', 'MI') # create a basic set of states and some cities in them cities = hashmap.new() hashmap.set(cities, 'CA', 'San Francisco') hashmap.set(cities, 'MI', 'Detroit') hashmap.set(cities, 'FL', 'Jacksonville') # add some more cities hashmap.set(cities, 'NY', 'New York') hashmap.set(cities, 'OR', 'Portland') # print out some cities print '-' * 10 print "NY State has: %s" % hashmap.get(cities, 'NY') print "OR State has: %s" % hashmap.get(cities, 'OR') # print some states print "-" * 10 print "Michigan's abbreviation is: %s" % hashmap.get(states, 'Michigan') print "Florida's abbreviation is: %s" % hashmap.get(states, 'Florida') # do it by using the state then cities dict print "-" * 10 print "Michigan has: %s" % hashmap.get(cities, hashmap.get(states, 'Michigan')) print "Florida has: %s" % hashmap.get(cities, hashmap.get(states, 'Florida')) # print every state abbreviation print "-" * 10 hashmap.list(states) # print every city in state print "-" * 10 hashmap.list(cities) print "-" * 10 state = hashmap.get(states, 'Texas') if not state: print "Sorry, no Texas" # default values useing //= with the nil result # can you do this on one line? city = hashmap.get(cities, 'TX', 'Does Not Exist') print "The city for the state 'TX' is: %s" % city # Yes, I can do this on one line. print 'The city for the state \'TX\' is: %s' % hashmap.get(cities, 'TX', 'Does Not Exist')
输出
Notes:
①列表是有序的,字典是key与value的映射且是无序的
②字典的items()方法,返回一个元组,该元组包括一对key-value;get(key[,return])返回key所对应的value,若key不存在且制订了return的值,返回return值,否则返回None
③列表的enumerate()函数,迭代时可以方便的获取索引和索引指向的元素
④hash()函数是哈希值函数,将对象转化为数字,对象不同,数字也不同