《Python Data Structures》Week5 Dictionary 课堂笔记
Coursera课程《Python Data Structures》 密歇根大学 Charles Severance
Week5 Dictionary
9.1 Dictionaries
字典就像是一个包,而这个包里的每样东西都整整齐齐地贴好了标签,于是我们可以通过标签来找到我们想要的东西。而且注意,字典这个包是无序的,所以它不能根据顺序索引,只能根据标签。
>>> purse = dict()
>>> purse['money'] = 12
>>> purse['candy'] = 3
>>> purse['tissues'] = 75
>>> print(purse)
{'money':12, 'tissues':75, 'candy':3}
>>> print(purse['candy'])
3
>>> purse['candy'] = purse['candy'] + 2
>>> print(purse)
{'money':12, 'tissues':75, 'candy': 5}
9.2 Counting with Dictionaries
我们可以使用"in"来查看,是否某个key在这个字典里。
>>> ccc = dict()
>>> print(ccc['csev'])
Traceback (most recent call last):
File "<stdin", line 1, in <module>
KeyError: 'csev'
>>> 'csev' in ccc
False
字典的get()方法是查看是否一个key已经在字典里,如果没有在的话,那就新建一个key,把它附上默认值。
比如下面这两段代码,其实功能是一样的。
if name in counts:
x = counts[name]
else:
x = 0
x = counts.get(name, 0)
所以使用get()来计数的话会更加方便。
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
counts[name] = counts.get(name, 0) + 1
print(counts)
输出结果就是
{'csev':2,'zqian':1,'cwen':2}
9.3 Dictionaries and Files
计数的一个基本模式是这样的。
counts = dict()
print('Enter a line of text:')
line = input('')
words = line.split()
print('Words:', words)
print('Counting...')
for word in words:
counts[word] = counts.get(word, 0) + 1
print('Counts', counts)
我们可以使用keys(), values(), items()这些方法来分别获得字典的key,值或者全部。
>>> jjj = {'chuck':1, 'fred':42, 'jan':100}
>>> print(list(jjj))
['jan', 'chuck', 'fred']
>>> print(jjj.keys())
['jan', 'chuck', 'fred']
>>> print(jjj.values())
[100, 1, 42]
>>> print(jjj.items())
[('jan', 100), ('chuck', 1), ('fred', 42)]
我们还可以使用两个循环变量同时对key和value进行循环。
jjj = {'chuck':1, 'fred':42, 'jan': 100}
for aaa,bbb in jjj.item():
print(aaa,bbb)
那么接下来我们就可以读取文件,来对里面的文本进行计数了。
name = input('Enter file:')
handle = open(name)
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
bigcount = None
bigword = None
for word, count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)
9.4 Assignment
作业的代码如下
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
words = line.split()
if len(words) < 1 or words[0] != 'From':
continue
counts[words[1]] = counts.get(words[1], 0) + 1
bigcount = None
bigword = None
for word, count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)
《Python Data Structures》Week5 Dictionary 课堂笔记的更多相关文章
- 【Python学习笔记】Coursera课程《Python Data Structures》 密歇根大学 Charles Severance——Week6 Tuple课堂笔记
Coursera课程<Python Data Structures> 密歇根大学 Charles Severance Week6 Tuple 10 Tuples 10.1 Tuples A ...
- 《Python Data Structures》 Week4 List 课堂笔记
Coursera课程<Python Data Structures> 密歇根大学 Charles Severance Week4 List 8.2 Manipulating Lists 8 ...
- 潭州课堂25班:Ph201805201 爬虫基础 第七课 Python与常见加密方式 (课堂笔记)
打开图形界面 18版 Python与常见加密方式 前言 我们所说的加密方式,都是对二进制编码的格式进行加密的,对应到Python中,则是我们的Bytes. 所以当我们在Python中进行加密操作的时 ...
- 学习笔记之Problem Solving with Algorithms and Data Structures using Python
Problem Solving with Algorithms and Data Structures using Python — Problem Solving with Algorithms a ...
- [译]The Python Tutorial#5. Data Structures
[译]The Python Tutorial#Data Structures 5.1 Data Structures 本章节详细介绍之前介绍过的一些内容,并且也会介绍一些新的内容. 5.1 More ...
- 剪短的python数据结构和算法的书《Data Structures and Algorithms Using Python》
按书上练习完,就可以知道日常的用处啦 #!/usr/bin/env python # -*- coding: utf-8 -*- # learn <<Problem Solving wit ...
- Python Tutorial 学习(五)--Data Structures
5. Data Structures 这一章来说说Python的数据结构 5.1. More on Lists 之前的文字里面简单的介绍了一些基本的东西,其中就涉及到了list的一点点的使用.当然,它 ...
- 《Data Structures and Algorithm Analysis in C》学习与刷题笔记
<Data Structures and Algorithm Analysis in C>学习与刷题笔记 为什么要学习DSAAC? 某个月黑风高的夜晚,下班的我走在黯淡无光.冷清无人的冲之 ...
- ocp11g培训内部教材_052课堂笔记(042)_体系架构
OCP 052 课堂笔记 目录 第一部分: Oracle体系架构... 4 第一章:实例与数据库... 4 1.Oracle 网络架构及应用环境... 4 2.Oracle 体系结构... 4 3. ...
随机推荐
- vue 项目报错,提示:Cannot read property '$createElement' of undefined at render ...
vue 项目报错,提示:Cannot read property '$createElement' of undefined at render ...
- webpack output的path publicPath
path是用来定义入口文件保存的地址,而publicPath是定义非入口文件需要抽离保存的第三方文件的保存地址 vue-cli 中HtmlWebpackPlugin生成html,都会存在path路径上 ...
- JS 的JSON对象
知识点一: 循环对象 for(x in Obj) x表示属性,Obj.x表示属性的值. 修改值 Obj.x = " "//直接修改 删除对象属性 delete Obj.x va ...
- Mysql数据库在建表时指定engine等于InnoDB 或MyISAM的意义
一.ISAM和InnoDB的定义 1. ISAM ISAM是一个定义明确且历经时间考验的数据表格管理方法,它在设计之时就考虑到数据库被查询的次数要远大于更新的次数.因此,ISAM执行读取操作的速度很快 ...
- redis防止抢购商品超卖
前言: redis不仅仅是单纯的缓存,它还有一些特殊的功能,在一些特殊场景上很好用. 本篇博文用来测试下使用redis来防止抢购商品超卖问题. 内容: 使用redis的list进行测试 思路是设置一个 ...
- Educational Codeforces Round 55 (Rated for Div. 2) B. Vova and Trophies (贪心+字符串)
B. Vova and Trophies time limit per test2 seconds memory limit per test256 megabytes inputstandard i ...
- 生成对抗网络资源 Adversarial Nets Papers
来源:https://github.com/zhangqianhui/AdversarialNetsPapers AdversarialNetsPapers The classical Papers ...
- oracle date函数
常用的时间格式 在oracle中有 yyyy-mm-dd hh24:mi:ss 而在Java中有些区别 为yyyy-MM-dd HH:mm:ss 这点还是经常容易模糊的.相信很多人都有过统计某些数据 ...
- 1.Linux命令行快捷键、Vim
1. 命令终端的快捷键使用 ctrl+b 左移光标 ctrl+f 右移光标 ctrl+u 删除光标左边的内容 ctrl+k 删除光标右边的内容 ctrl+w 删除光标前的一个单词 =esc+ctrl+ ...
- R语言-变量命名规则
1.大原则:只有字母(区分大小写).数字.“_”(下划线).“.”(英文句号)可以出现. 2.数字.下划线不能开头. 3.英文句号开头不能紧接数字. 就这么简单!