笨办法学python第38节
如何创建列表在第32节,形式如下:
本节主要是讲对列表的操作,首先讲了 mystuff.append('hello') 的工作原理,我的理解是,首先Python找到mystuff这个变量,然后进行append()这个函数操作。其中需要注意的是括号()里面有一个额外参数就是mystuff本身。
本文练习:
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'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 (why not sequence)
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
# safely get a abbreviation by state that might not be there
state = states.get('Texas', None) if not state:
print "Sorry, 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
存在的问题:
1. 40行的输出城市名称,运行时输出的并不是顺序输出的,这个输出遵循的规律是什么?
2. states.items(),按照书里说的()里面有一个额外参数states,所以在这个()里面不加参数,因为里面的参数就是前面的列表,那如果想再加一个参数在()里面,如何加?
回答:
1. Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
dict内部存放的顺序和key放入的顺序是没有关系的,dict的查找是根据哈希表查找的,所以输出不是顺序输出的。
2. 这个和书里的那个函数不一样,书里的那个函数是append(),这个item()相当于遍历这个列表,所以后面不再加参数。