Tuple是受限制的List
1.Tuple和List的区别:
1)形式上的区别:()与[]
x = ('Sally', 'John', 'Leo') # Tuple
y = ['Sally', 'John', 'Leo'] # List
2)使用时的区别
Tuple初始化后无法被更改,像Str一样
# List初始化后可以被更改
x = [9, 8, 7]
x[2] = 6
print(x)
# [9, 8, 6]
# Tuple初始化后不能被更改
z = (5, 4, 3)
z[2] = 0
# Traceback: 'tuple' object does not support item Assignment
同时,Tuple内的元素不能被排序、添加和翻转等
2.Tuple的神奇用法
1)建立1对1的对应关系,变量赋值更简洁
(x, y) = (4, 'fred')
print(y) # fred
(a, b) = (99, 98)
print(a) # 99
2)Tuple什么时候出现在Dictionary中?
当Dictionary使用item()时
The items() method in dictionaries returns a list of (key, value) tuples
d = dict()
d['csev'] = 2
d['cwen'] = 4
for (k, v) in d.items() :
print(k, v)
# csev 2
# cwen 4
tups = d.items()
print(tups)
# dict_items([('csev', 2), ('cwen', 4)])
# 由Tuple元素组成的List
3)不同的Tuple可以被比较
print((0, 1, 2000000) < (0, 3, 4)) # True
print(('Jones', 'Sally') < ('Jones', 'Sam')) # True
4)利用Tuple可以被比较的特性对dictionary排序(by key)
d = {'b':1, 'a':10, 'c':22}
t = sorted(d.items()) # 首先根据dictionary的key值排序
print(t)
# [('a', 10), ('b', 1), ('c', 22)]
for k, v in sorted(d.items()):
print(k, v)
# a 10
# b 1
# c 22
5)Sort by Values Instead of Key
If we could construct a list of tuples of the form (value, key) we could sort by value
c = {'a':10, 'b':1, 'c':22}
tmp = list()
for k, v in c.items() :
tmp.append((v, k))
print(tmp)
# [(10, 'a'), (1, 'b'), (22, 'c')]
tmp = sorted(tmp, reverse = True) #倒序
print(tmp)
# [(22, 'c'), (10, 'a'), (1, 'b')]
Even Shorter Version
c = {'a':10, 'b':1, 'c':22}
print(sorted([(v, k) for k, v in c.items()]))
# [(1, 'b'), (10, 'a'), (22, 'c')]
实例:
寻找txt文件中出现最多的10个单词
#打开文件,统计词数
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()
# dict的items()是一个元素种类为tuple的list
for k, v in counts.items():
newtup = (v, k)
lst.append(newtup)
#倒序排序
lst = sorted(lst, reverse = True)
#上述排序准备和排序可简化为1行
# lst = sorted([(v, k) for k, v in counts.items()], reverse = True)
#输出前10个高频词
for v, k in lst[:10]:
print(k, v)