元组

'''
tup1 = ()          #创建一个空的元组
print(type(tup1))
#tup2 = (50)     #不是元组,python把括号当成了表达式的一部分,即数学运算的括号
#tup2 = (50,)
tup2 = (50,60,70)
print(type(tup2))
'''
'''
tup1 = ("abc","def",2020,2023,111,222,333)
print(tup1[0])
print(tup1[-1])
print(tup1[1:5]) #左闭右开,进行切片
'''
# 增 (连接)
'''
tup1 = (60,70,80)
tup2 = ("abc","xyz")
tup = tup1 + tup2
print(tup)
'''
# 删 只能删除整个元组
'''
tup1 = (60,70,80)
print(tup1)
del tup1
print("删除后:",tup1)
'''
# 改
'''
tup1 = (50,60,70)
tup1[0] = 100  #报错,元组不允许修改
'''
# 查 直接输出下标
tup1 = ("abc","def",2020,2023,111,222,333)
print(tup1[0])

字典

即键值对,键必须是唯一的

'''
#字典的定义
info = {"name":"吴彦祖","age":18}
#字典的访问
print(info["name"])
print(info["age"])
# 访问不存在的键
#print(info["gender"])          #直接访问会报错
#print(info.get("gender"))       #使用get方法,访问不存在的键,默认返回:None
print(info.get("age",20))
print(info.get("gender","m"))      #没找到,可以设定默认值
'''
# 增
'''
info = {"name":"吴彦祖","age":18}
newID = input("请输入:")
info["id"] = newID
print(info["id"])
'''
# 删
'''
#del 删除
info = {"name":"吴彦祖","age":18}
print("删除前:%s"%info["name"])
del info["name"]            #删除了整个键值对
print("删除后%s"%info["name"])  #再次访问会报错
info = {"name":"吴彦祖","age":18}
print("删除前:%s"%info)
del info
print("删除后:%s"%info)
#clear 清空
info = {"name":"吴彦祖","age":18}
print("清空前:%s"%info)
info.clear()
print("清空后:%s"%info)
'''
# 改 直接改
'''
info = {"name":"吴彦祖","age":18}
info["age"] = 20
print(info["age"])
'''
# 查 (遍历)
'''
info = {"id":1,"name":"吴彦祖","age":18}
print(info.keys())          #得到所有的键(列表)
print(info.values())        #得到所有的值(列表)
print(type(info.keys()))
print(info.items())         #得到所有的项,每个键值对是一个元组
#遍历所有的键
for key in info.keys():
    print(key)
#遍历所有的键值对
for key,value in info.items():
    print("key = %s,value = %s"%(key,value))
'''
#使用枚举函数同时获得列表的下标和元素
a = ["小明","小红","小李","小张"]
for i,j in enumerate(a):
    print(i+1,j)

发表回复