learn python the hard way(笨办法学python) 练习39
2016-02-22 09:08
211 查看
练习39中,我们主要学会了运用字典。
下面来介绍一下书中没有介绍到的知识点:
stuff字典中,‘name' 称为key(键),’Zed‘ 称为Value(值)。
本篇练习中,比较难理解的有以下几点:
1.dicts中,for循环的运用
这段程序当中,for循环和以往学的不一样,原因是我们使用的是字典中每个单元由分别由key和value组成,如:
所以,这里的for循环中的字符串需要两个变量来赋值,in后面也要变成states.item()
2.dict.get()的运用
Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。
key -- 字典中要查找的键。
default -- 如果指定键的值不存在时,返回该默认值值。
书中例题:
可另写以下程序来认识dict.get()的运用:
我们也可以把这段程序写得更有趣一些:
下面来介绍一下书中没有介绍到的知识点:
stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
stuff字典中,‘name' 称为key(键),’Zed‘ 称为Value(值)。
本篇练习中,比较难理解的有以下几点:
1.dicts中,for循环的运用
for state, abbrev in states.items(): print "%s is abbreviated %s" % (state, abbrev)
这段程序当中,for循环和以往学的不一样,原因是我们使用的是字典中每个单元由分别由key和value组成,如:
states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' }
所以,这里的for循环中的字符串需要两个变量来赋值,in后面也要变成states.item()
2.dict.get()的运用
Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。
dict.get(key, default=None)
key -- 字典中要查找的键。
default -- 如果指定键的值不存在时,返回该默认值值。
书中例题:
state = states.get('Texas') if not state: print "Sorry, no Texas." city = cities.get('TX', 'Does Not Exist') print "The city for the state 'TX' is: %s" % city
可另写以下程序来认识dict.get()的运用:
state = states.get('Oregon') if state: print "YES." else: print "NO." city = cities.get('CA', 'Does Not Exist') print "The city for the state 'CA' is: %s" % city
我们也可以把这段程序写得更有趣一些:
print "Let's search the abbreviation of the state." a = raw_input( "state's name:") state = states.get(a) if state: print "The %s 's abbrev is %s"% (a, state) else: print "Sorry, cannot find this state." # get a city with a default value print "Let's search which city is in the state." b = raw_input( "state's abbreviation:") city = cities.get(b, 'Does Not Exist') print "The city for the state '%s' is: %s" % (b, city)
相关文章推荐
- python实现识别相似图片小结
- python 模块
- python实现识别相似图片小结
- python实现搜索本地文件信息写入文件的方法
- python文件操作相关知识点总结整理
- python文件与目录操作实例详解
- python开发之str.format()用法实例分析
- python开发之list操作实例分析
- python 3 pyenv版本管理与pymsql、paramiko模块
- 【福利】Python入门基础知识大盘点
- spark python编程
- 利用python求解八数码难题
- Python-练习 洗牌
- 《笨办法学Python》 第42课手记
- python pygame安装与使用问题
- python基础学习,基础语法总结
- 已知线段端点坐标,求线段上等距离的点坐标序列
- 已知四边形四个顶点坐标,求面积
- 已知两点经纬度坐标,求其直线距离
- python字符串总结