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)