标签:
笨办法学python第38节
如何创建列表在第32节,形式如下:
本节主要是讲对列表的操作,首先讲了 mystuff.append(‘hello‘) 的工作原理,我的理解是,首先Python找到mystuff这个变量,然后进行append()这个函数操作。其中需要注意的是括号()里面有一个额外参数就是mystuff本身。
本文练习:
1 # create a mapping of state to abbreviation 2 states = { 3 ‘Oregon‘: ‘OR‘, 4 ‘Florida‘: ‘FL‘, 5 ‘California‘: ‘CA‘, 6 ‘Michigan‘: ‘MI‘ 7 } 8 9 # create a basic set of states and some cities in them 10 cities = { 11 ‘CA‘: ‘San Francisco‘, 12 ‘MI‘: ‘Detroit‘, 13 ‘FL‘: ‘Jacksonville‘ 14 } 15 16 # add some more cities 17 cities[‘NY‘] = ‘New York‘ 18 cities[‘OR‘] = ‘Portland‘ 19 20 # print out some cities 21 print ‘-‘ * 10 22 print "NY State has: ", cities[‘NY‘] 23 print "OR State has: ", cities[‘OR‘] 24 25 # print some states 26 print ‘-‘*10 27 print "Michigan‘s abbreviation is: ", states[‘Michigan‘] 28 print "Florida‘s abbreviation is: ", states[‘Florida‘] 29 30 # do it by using the state then cities dict 31 print ‘-‘*10 32 print "Michigan has: ", cities[states[‘Michigan‘]] 33 print "Florida has: ", cities[states[‘Florida‘]] 34 35 # print every state abbreviation 36 print ‘-‘*10 37 for state, abbrev in states.items(): 38 print "%s is abbreviated %s" % (state, abbrev) 39 40 # print every city in state (why not sequence) 41 print ‘-‘*10 42 for abbrev, city in cities.items(): 43 print "%s has the city %s" % (abbrev, city) 44 45 # now do both at the same time 46 print ‘-‘*10 47 for state, abbrev in states.items(): 48 print "%s state is abbreviated %s and has city %s" % ( 49 state, abbrev, cities[abbrev]) 50 51 print ‘-‘*10 52 # safely get a abbreviation by state that might not be there 53 state = states.get(‘Texas‘, None) 54 55 if not state: 56 print "Sorry, no Texas." 57 58 # get a city with a default value 59 city = cities.get(‘TX‘, ‘Does Not Exist‘) 60 print "The city for the state ‘TX‘ is: %s" % city
存在的问题:
1. 40行的输出城市名称,运行时输出的并不是顺序输出的,这个输出遵循的规律是什么?
2. states.items(),按照书里说的()里面有一个额外参数states,所以在这个()里面不加参数,因为里面的参数就是前面的列表,那如果想再加一个参数在()里面,如何加?
回答:
1. Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
dict内部存放的顺序和key放入的顺序是没有关系的,dict的查找是根据哈希表查找的,所以输出不是顺序输出的。
2. 这个和书里的那个函数不一样,书里的那个函数是append(),这个item()相当于遍历这个列表,所以后面不再加参数。
标签:
原文地址:http://www.cnblogs.com/EiffelRachel/p/5891894.html