1元组
# 一个元组可以存储多个数据,但是元组内的数据不可以修改
# 多个数据元组
t1 = (10, 20, 30)
# 单个数据元组
t2 = (10,)
# 查找
tuple1 = ('aa', 'bb', 'cc')
print(tuple1[0]) # aa
print(tuple1.index('aa')) # 0 找不到的话会报错
print(tuple1.count('bb')) # 1
print(len(tuple1)) # 3
# 修改
# 元组内的直接数据如果修改会报错
# 但是如果元组里面有列表,修改列表里面的数据则是可以的
tuple2 = (10, 20, ['aa', 'bb', 'cc'], 40, 50)
tuple2[2][0] = 'aba'
print(tuple2) # (10, 20, ['aba', 'bb', 'cc'], 40, 50)
2字典
创建字典
# 字典里面的数据是以键值对形式出现
# 有效字典
dict1 = {'name': 'Tom', 'age' : 20, 'gender' : '男'}
# 空字典
dict2 = {}
dict3 = dict();
CRUD
# 增 如果key存在则修改,否则新增此键值对
dict1 = {'name': 'Tom', 'age' : 20, 'gender' : '男'}
dict1['name'] = 'Rose'
print(dict1) # {'name': 'Rose', 'age': 20, 'gender': '男'}
dict1['id'] = 110
print(dict1) # {'name': 'Rose', 'age': 20, 'gender': '男', 'id': 110}
# 删 del()/del 删除字典或删除字典中指定键值对
dict1 = {'name': 'Tom', 'age' : 20, 'gender': '男'}
del dict1['gender']
# del(dict1) 删除字典
print(dict1) # {'name': 'Tom', 'age': 20}
dict1.clear()
print(dict1) # {}
# 修改
dict1 = {'name': 'Tom', 'age' : 20, 'gender': '男'}
dict1['name'] = 'gaopeng'
print(dict1)
dict1['id'] = 110
# 和增加一回事
# 查找
# 1 key值查找
dict1 = {'name': 'Tom', 'age' : 20, 'gender': '男'}
print(dict1['name']) # Tom
# print(dict1['id']) # 报错
# 2 get(key,默认值)
# 如果当前查找的key不存在则返回第二个默认值(默认值),如果省略第二个参数,则返回None
print(dict1.get('name')) #
print(dict1.get('id', '没找到')) # 没找到
print(dict1.get('id')) # None
# 2 keys()
print(dict1.keys()) # dict_keys(['name', 'age', 'gender'])
# 3 values()
print(dict1.values()) # dict_values(['Tom', 20, '男'])
# 4 items()
print(dict1.items()) # dict_items([('name', 'Tom'), ('age', 20), ('gender', '男')])
# 字典的循环遍历
# 1 遍历字典的key
dict1 = {'name': 'Tom', 'age' : 20, 'gender': '男'}
for key in dict1.keys():
print(key, end=' ')
else:
print()
# name age gender
# 2 遍历value
for value in dict1.values():
print(value, end=' ')
else:
print()
# Tom 20 男
# 3 遍历字典的元素
for item in dict1.items():
print(item, end=' ')
else:
print()
# ('name', 'Tom') ('age', 20) ('gender', '男')
# 4 遍历字典的键值对(拆包)
for key, value in dict1.items():
print(f'{key} : {value}', end=' ')
else:
print()
# name : Tom age : 20 gender : 男
3集合
#创建集合 使用{}或者set()
s1 = {10, 20, 30, 40, 50}
s2 = set('abcdef')
s3 = set()
s4 = {} # 这个就不是集合了,是dict,字典
s1 = {10, 20}
# 增加数据
s1.add(100)
s1.add(10)
print(s1) # {100, 10, 20}
# update() 追加的数据时序列
# s1.update(200) # 报错
s1.update([200, 300])
s1.update('abc')
print(s1) # {100, 200, 10, 300, 20, 'a', 'c', 'b'}
# 删除数据
s1 = {10, 20, 39, 40}
s1.remove(10)
print(s1) # {40, 20, 39}
# s1.remove(10)
# print(s1) # 报错
# discard() 删除集合中的指定数据,如果数据不存在也不会报错
s1.discard(20)
print(s1) # {40, 39}
s1.discard(20)
print(s1) # {40, 39}
# pop() 随机删除集合中的某个数据,并返回这个数据
# 查找数据
# in not in
s1 = {10, 20, 30, 40, 50}
print(10 in s1) # True
print(10 not in s1) # False