Python-tuple(课堂笔记整理)

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内的元素不能被排序、添加和翻转等
Tuple
Tuple and List
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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值