Python基础入门(四)
一、本课目标
- 理解并掌握 “元组” 的概念及使用
- 理解并掌握 “字典” 的概念及使用
- 理解并掌握 “集合” 的概念及使用
二、元组
-
元组与列表类似,不同之处在于元组的元素不能修改
-
元组使用小括号(),列表使用方括号[ ]
-
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可
-
元组中只包含一个元素时,需要在元素后面添加逗号
-
元组与字符串类似,下标索引从0开始,可以进行截取,组合等
l = ['a', 'b', 'c'] t = ('a', 'b', 'c') l += 'd' l += ['b'] t += ('b', ) del l[0] print(l, t) t1 = (1, 2, 3) t2 = (4, 5, 6) t3 = t1 + t2 print(t3) t1 = (1, 2, 3) t1 += (4, 5, 6) t2 = t1 print(t1) print(t2) a = '12' print(id(a[0]), id(a[1]), id(a)) a = a.replace('1', '2') print(id(a[0]), id(a[1]), id(a)) b = [1, 2] print(id(b[0]), id(b[1]), id(b)) b[0] = 2 print(id(b[0]), id(b[1]), id(b)) for i in ('a', 'b', 'c'): print(i) t = ('12', '012', '21') print(max(t), min(t)) t = (16, 78, 89) print(max(t), min(t)) l = [1,2,3] t = tuple(l) print(t)
-
练习一:
tupe1 = ('Google', 'Apache', '1997', 2000) tupe2 = (1, 2, 3, 4, 5, 6) print("tup1[0]:", tupe1[0]) print("tup2[1:5]:", tupe2[1:5]) tup1 = (12, 34.56) tup2 = ('abc', 'xyz') tup3 = tup1 + tup2 print(tup3) print(len((1, 2, 3))) a = (1, 2, 3) b = (4, 5, 6) c = a + b print(c) a += b print(a) print(('Hi!,' * 4)) print(3 in (1, 2, 3)) for x in (1, 2, 3): print(x, end='')
-
练习二:
tup = ('Google', 'Apache', 'Taobao', 'Wiki', 'Weibo', 'Weixin') print(tup[1]) print(tup[-2]) print(tup[1:]) print(tup[1:4]) tuple1 = ('Google', 'Apache', 'Taobao') print(len(tuple1)) tuple2 = ('5', '4', '8') print(max(tuple2)) print(min(tuple2)) list1 = ['Google', 'Apache', 'Taobao', 'Baidu'] tuple1 = tuple(list1) print(tuple1)
三、字典的概念
- 字典是另一种可变容器模型,且可存储任意类型对象
- 字典的每个键值key = >value对用冒号:分隔,每个对之间用逗号(,)分隔,整个字典包括在花括号{}中,格式如下所示:
- d = {key1: value1, key2 : value2, key3 : value3}
- 键必须是唯一的,但值则不必
四、字典操作
-
创建空字典
- 使用大括号{ }
- 使用函数dict()
-
访问字典里的值
- 通过[键]
- 通过 for in
-
修改字典
- 通过字典[值] = 值 添加或更新
- 通过del字典[键]删除
#字典
d = {
}
print(tuple(d))
d = {
'a':1, 'b':2, 'c':3}
print(d)
d = {
'a':1, 'b':2, 'c':3, 'a':7, 5:6}
print(d)
d = dict(a=1, b=2, c=3)
print(d)
d = {
'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
print(d['c'])
print(d['f']) # error
for i in d.items():
print(i)
for k,v in d.items():
print(k, v)
for k in d:
print(k)
for k in d.keys():
print(k)
for v in d.values():
print(v)
for k in d:
print(k, d[k])
d= {
'apple':