《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. ...
随机推荐
- 2014-04-27 南江滨大道 6KM 晴
33分41秒,6.03公里,慢速跑,中间有停了几次拍照 天气不错,多云 人,不多 不知道这货叫啥 2个大人3个小孩,跳绳,小时候的回忆,啊哈 老中少三代,捡风筝也是一种幸福 一家三口,江滨散步,惬意至 ...
- web框架-(三)Django进阶
通过上节课的学习,我们已经对Django有了简单的了解,现在来深入了解下~ 1. 路由系统 1.1 单一路由对应 url(r'^index$', views.index), 1.2 基于正则的路由 u ...
- ssh跳板到其他服务器
https://my.oschina.net/foreverich/blog/657075 http://mingxinglai.com/cn/2015/07/ssh-proxycommand/ 查看 ...
- bzoj5089 最大连续子段和 分块+复杂度分析+凸包
题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=5089 题解 本来打算迟一点再写这个题解的,还有一个小问题没有弄清楚. 不过先写一下存个档吧. ...
- Spring源码--Bean的管理总结(一)
前奏 最近看了一系列解析spring管理Bean的源码的文章,在这里总结下,方便日后复盘.文章地址https://www.cnblogs.com/CodeBear/p/10336704.html sp ...
- 使用HTML和CSS来实现为文字设置图片底纹
先看一下最终实现的效果 图中的hello是文本而不是图片 那么如何实现这种效果呢? HTML部分: 创建一个h1标签 ,标签内容为(hello).通过link标签链接外部样式表style.css. s ...
- moment使用,把某个时间时间戳转换成日期
1.某个时间时间戳转换成日期 moment(时间戳 ).format("YYYYMMDD") 2.获取某个日期当月的最后一天 moment(“2019-04-05”).endO ...
- Spring配置:用context:property-placeholder替换PropertyPlaceholderConfigurer
1.有时候需要从properties文件中加载配置,以前的方式是这样的: <bean id="jdbcProperties" class="org.springfr ...
- BZOJ 3887: [Usaco2015 Jan]Grass Cownoisseur tarjan + spfa
Code: #include <bits/stdc++.h> #define setIO(s) freopen(s".in","r",stdin) ...
- 字符串截取模板 && POJ 3450、3080 ( 暴力枚举子串 && KMP匹配 )
//截取字符串 ch 的 st~en 这一段子串返回子串的首地址 //注意用完需要根据需要最后free()掉 char* substring(char* ch,int st,int en) { ; c ...