10. 元组、集合
元组的创建方式
1. 使用小括号 () t = (1,2,3)
2. 使用内置函数 tuple(). t1 = tuple((1,2,3,4))
如果只创建一个元素的元组,必须要有逗号 t2 = (1,)
元组的元素id不能改变
t = (1, [0,1,2], '222')
t[0] = 2 直接赋值会报错,但是可以改变列表的值,比如 t[1].append(3)
元组是可迭代对象,可以使用for in 遍历
def tuple_test():
t = ()
t1 = tuple()
t2 = tuple((1, 2, 3))
print(t, t1, t2)
t = (1, [0, 1, 2], '222')
t[1].append(3)
print(t) # (1, [0, 1, 2, 3], '222')
集合
内置的数据结构
与列表,字典一样都属于可变类型的序列
集合是没有value的字典
集合是无序的
创建方式:
使用 花括号 s = {1,2,4,5}
使用内置函数set() s = set(1,24,5)
创建空集合,只能使用 set() 如果使用 花括号 则类型为字典
集合的判断: in 或者 not in 集合元素的新增操作: add(), 一次添加一个元素 update(),至少添加一个元素, 可以添加 元组,集合,列表 删除: remove(), 一次删除一个元素,如果不存在抛出key Error discard(),一次删除一个元素,如果不存在不抛出异常 pop(), 一次只删除一个任意元素, 不能加参数 clear(), 清空集合
def set_test():
s = {1, 22, 44, 6, 7, 4}
print(s, type(s))
print(set([1, 2, 4, 5, 6, 7, 7, 8, 9]))
print(set((1, 22, 4, 55, 66, 77, 77, 8)))
print(set('python')) # {'y', 'h', 'n', 't', 'o', 'p'}
print(set({124, 55, 33, 55, 4, 2, 2}))
print(set())
print(1 in s)
print(22 not in s)
s.add(888)
print(s)
s.update({100, 200})
print(s)
s.update([1, 3, 4, 511])
print(s)
s.update((1, 3, 4, 5, 6, 7, 8, 9, 1111))
print(s)
s.remove(100)
print(s)
s.discard(188)
print(s)
s.pop()
print(s)
s.clear()
print(s)
集合的数学操作 交集: intersection 或者 & 并集:union 或者 | 差集:difference 或者 - 对称差集:symmetric_difference 或者 ^ 集合生成式: 同列表生成式一样,把方括号换成花括号 列表:[i*i for i in range(6)] 集合:{i*i for i in range(6)}
def set_math():
s1 = {10, 20, 30, 40}
s2 = {20, 30, 40, 50, 60}
print(s1.intersection(s2), s1 & s2) # 交集
print(s1.union(s2), s1 | s2) # 并集
print(s1.difference(s2), s1 - s2) # 差集,A集合的内容去掉B集合有的内容
print(s1.symmetric_difference(s2), s1 ^ s2) # 对称差集,两个集合的所有不同值
总结: