Coursera课程《Python Data Structures》 密歇根大学 Charles Severance

Week6 Tuple

10 Tuples

10.1 Tuples Are Like Lists

元组是另外一种序列,它的方法和list挺像的。它的元素也是从0开始计数。

>>> x = ('Glenn', 'Sally', 'Joseph')
>>> print(x[2])
Joseph
>>> y = (1, 9, 2)
>>> print(y)
(1, 9, 2)
>>> print(max(y))
9
>>> for iter in y:
... print(iter)
...
1
9
2

10.2 but... Tuples are "immutable"

不像list,一旦你创建了一个元组,你是不能修改它的内容的,这和string很相似。

## list
>>> x = [9, 8, 7]
>>> x[2] = 6
>>> print(x)
[9, 8, 6] ## string
>>> y = 'ABC'
>>> y[2] = 'D'
Traceback:'str' object does not support item Assignment ## tuples
>>> z = (5, 4, 3)
>>> z[2] = 0
Traceback: 'tuple' object does not support item Assignment

10.3 Things not to do With Tuples

有一些list的方法,元组是不能使用的,其原因还是元组是不可更改的。

>>> x = (3, 2, 1)
>>> x.sort()
Traceback:
AttributeError: 'tuple' object has no attribute 'sort'
>>> x.append(5)
Traceback:
AttributeError: 'tuple' object has no attribute 'append'
>>> x.reverse()
Traceback:
AttributeError: 'tuple' object has no attribute 'reverse'

10.4 A Tale of Two Sequences

可以看下list和tuple的方法都有什么不同。

>>> l = list()
>>> dir(l)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> t = tuple()
>>> dir(t)
['count', 'index']

10.5 Tuples Are More Efficient

因为Python不需要构建可以修改的数据结构给元组,所以元组在内存使用等方面会比列表更加简单与高效。

所以当我们在程序中构建“临时变量”时,我们更喜欢使用元组而不是列表。

10.6 Tuples and Assignment

我们还可以使用元组来申明变量。

>>> (x, y) = (4, 'fred')
>>> print(y)
fred
>>> (a, b) = (99, 98)
>>> print(a)
99

10.7 Tuples and Dictionaries

还记得之前学过的字典吗?如果使用item()这个方法,我们就会得到一个由(key, value)组成的元组的列表。

10.8 Tuples are Comparable

元组是可以配对进行比较的。它的原则是,如果两边的第一项是相等的,那么就跳到两边的第二项进行比较,以此类推,直到找到元素是不相等的。

>>> (0, 1, 2) < (5, 1, 2)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
>>> ('Jones', 'Sally') < ('Jones', 'Sam')
True
>>> ('Jones', 'Sally') > ('Adams', 'Sam')
True

10.9 Sorting Lists of Tuples

我们可以使用元组列表对一个字典进行排序。

是这样的,我们可以首先用items()方法把key和value取出来,形成一个元组列表,然后使用sort()对其进行排序。注意,这样我们最后得到的是一个以key排序的元组列表。

>>> d = {'a':10, 'b':1, 'c':22}
>>> d.items()
dict_items([('a', 10), ('c', 22), ('b', 1)])
>>> sorted(d.items())
[('a', 10), ('b', 1), ('c', 22)]

那么如果我们想要以value排序呢?只需要使用一个for循环生成一个新的元组列表。

>>> c = {'a':10, 'b':1, 'c':22}
>>> tmp = list()
>>> for k, v in c.items():
... temp.append((v, k))
...
>>> print(temp)
[(10, 'a'), (22, 'c'), (1, 'b')]
>>> print(temp)
[(22, 'c'), (10, 'a'), (1, 'b')]

10.10 The top 10 most common words

fhand = open('romeo.txt')
counts = dict()
for line in fhand:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1 lst = list()
for key, val in counts.items():
newtup = (val, key)
lst.append(newtup) lst = sorted(lst, reverse=True) for val, key in lst[:10]:
print(key, val)

10.11 Even Shorter Version

以上代码或者可以略缩一些,可代替8-16行的代码。

>>> c = {'a': 10, 'b':1, 'c':22}
>>> print(sorted([(v, k) for k, v in c.items()]))
[(1, 'b'), (10, 'a'), (22, 'c')]

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
time = words[5].split(':')
counts[time[0]] = counts.get(time[0], 0) + 1 lst = list()
for key, val in counts.items():
newtup = (key, val)
lst.append(newtup) lst = sorted(lst) for key, val in lst:
print(key, val)

【Python学习笔记】Coursera课程《Python Data Structures》 密歇根大学 Charles Severance——Week6 Tuple课堂笔记的更多相关文章

  1. 【Python学习笔记】Coursera课程《Using Python to Access Web Data》 密歇根大学 Charles Severance——Week6 JSON and the REST Architecture课堂笔记

    Coursera课程<Using Python to Access Web Data> 密歇根大学 Week6 JSON and the REST Architecture 13.5 Ja ...

  2. 【Python学习笔记】Coursera课程《Using Python to Access Web Data 》 密歇根大学 Charles Severance——Week2 Regular Expressions课堂笔记

    Coursera课程<Using Python to Access Web Data > 密歇根大学 Charles Severance Week2 Regular Expressions ...

  3. 【C语言】Coursera课程《计算机程式设计》台湾大学刘邦锋——Week6 String课堂笔记

    Coursera课程 <计算机程式设计>台湾大学 刘邦锋 Week6 String 6-1 Character and ASCII 字符变量的声明 char c; C语言使用一个位元组来储 ...

  4. 【Python学习笔记】Coursera课程《Using Databases with Python》 密歇根大学 Charles Severance——Week4 Many-to-Many Relationships in SQL课堂笔记

    Coursera课程<Using Databases with Python> 密歇根大学 Week4 Many-to-Many Relationships in SQL 15.8 Man ...

  5. 《Using Python to Access Web Data》Week4 Programs that Surf the Web 课堂笔记

    Coursera课程<Using Python to Access Web Data> 密歇根大学 Week4 Programs that Surf the Web 12.3 Unicod ...

  6. python学习第八讲,python中的数据类型,列表,元祖,字典,之字典使用与介绍

    目录 python学习第八讲,python中的数据类型,列表,元祖,字典,之字典使用与介绍.md 一丶字典 1.字典的定义 2.字典的使用. 3.字典的常用方法. python学习第八讲,python ...

  7. python学习第七讲,python中的数据类型,列表,元祖,字典,之元祖使用与介绍

    目录 python学习第七讲,python中的数据类型,列表,元祖,字典,之元祖使用与介绍 一丶元祖 1.元祖简介 2.元祖变量的定义 3.元祖变量的常用操作. 4.元祖的遍历 5.元祖的应用场景 p ...

  8. python学习第六讲,python中的数据类型,列表,元祖,字典,之列表使用与介绍

    目录 python学习第六讲,python中的数据类型,列表,元祖,字典,之列表使用与介绍. 二丶列表,其它语言称为数组 1.列表的定义,以及语法 2.列表的使用,以及常用方法. 3.列表的常用操作 ...

  9. python学习第四讲,python基础语法之判断语句,循环语句

    目录 python学习第四讲,python基础语法之判断语句,选择语句,循环语句 一丶判断语句 if 1.if 语法 2. if else 语法 3. if 进阶 if elif else 二丶运算符 ...

随机推荐

  1. 调度的log 1.5ms 12ms 4ms

    36   37   38            loopM 24369 [001] 60789.192708: sched:sched_switch: prev_comm=loopM prev_pid ...

  2. 【.Net】浅谈C#中的值类型和引用类型

    在C#中,值类型和引用类型是相当重要的两个概念,必须在设计类型的时候就决定类型实例的行为.如果在编写代码时不能理解引用类型和值类型的区别,那么将会给代码带来不必要的异常.很多人就是因为没有弄清楚这两个 ...

  3. 【bzoj1707】[Usaco2007 Nov]tanning分配防晒霜 贪心+Treap

    题目描述 奶牛们计划着去海滩上享受日光浴.为了避免皮肤被阳光灼伤,所有C(1 <= C <= 2500)头奶牛必须在出门之前在身上抹防晒霜.第i头奶牛适合的最小和最 大的SPF值分别为mi ...

  4. openstack之Glance介绍

    什么是Glance glance即image service(镜像服务),是为虚拟机的创建提供镜像服务 为什么要有Glance 我们基于openstack是构建基本的Iaas平台对外提供虚机,而虚机在 ...

  5. UVA.699 The Falling Leaves (二叉树 思维题)

    UVA.699 The Falling Leaves (二叉树 思维题) 题意分析 理解题意花了好半天,其实就是求建完树后再一条竖线上的所有节点的权值之和,如果按照普通的建树然后在计算的方法,是不方便 ...

  6. apache出现You don't have permission to access / on this server. 提示

    今天在新的linux上跑原来的代码,使用的虚拟主机的模式进行操作.几个相关的网站放在一个文件里,想法是通过网站列出的目录进行相应的网站进行操作.一切设置完成后,在浏览器中运行出现在You don't ...

  7. JS获取移动端系统信息(操作系统、操作系统版本、横竖屏状态、设备类型、网络状态、生成浏览器指纹)

    function getOS() { // 获取当前操作系统 var os; if (navigator.userAgent.indexOf('Android') > -1 || navigat ...

  8. JavaScript Date的原型方法扩展

    在JavaScript开发中,经常需要对Date类型的对象进行各种验证或格式化,但是js并没有提供那么多的那么细的函数,所以只好自己去用 prototype 扩充了,下面是我自己实现的Date类型常用 ...

  9. 关于springmvc下服务器文件打包成zip格式下载功能

    关于springmvc下服务器文件打包成zip格式下载功能 2016年09月21日 11:22:14 toxic_guantou 阅读数:5731更多 个人分类: 技术点存储   版权声明:本文为博主 ...

  10. 挖一挖unsigned int和补码

    文章要讨论的是两部分: 1. 原码,反码和补码. 2. short, unsigned short, int, unsigned int, long, unsigned long的表示及转换 1. 原 ...