Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号
元组格式
格式
变量名=(,,,,)
案例
aa=(13,54,56,33,23)
访问元组
通过索引获取数据
案例:索引值存在
aa=(13,54,56,33,23)
print(aa[2])
#56
案例:索引值不存在
aTuple=(23,35,56,34,11,21)
print(aTuple[20])
#IndexError: tuple index out of range
查询个数
count查询出现的个数
案例
aTuple=('b','c','d','e','f','g')
print(aTuple.count('d'))
#1
查询索引
index:查询元素的索引,有对应的元素返回对应的索引,否则报错
有对应的元素
aTuple=('b','c','d','e','f','g')
print(aTuple.index('d',0,4))
#2
无对应的元素
aTuple=('b','c','d','e','f','g')
print(aTuple.index('d',0,1))
#ValueError: tuple.index(x): x not in tuple
修改数据(不能修改)
aTuple=('b','c','d','e','f','g')
aTuple[1]=23
#TypeError: 'tuple' object does not support item assignment
类型转换
列表转换元组
aa = [23,34,45,56,67]
tuple(aa)
print(aa)
#[23, 34, 45, 56, 67]
元组转换列表
aTuple=('b','c','d','e','f','g')
a = list(aTuple)
print(a)
#['b', 'c', 'd', 'e', 'f', 'g']
元组的循环取值
方式一:for
aTuple=('b','c','d','e','f','g')
for i in aTuple:
print(i)
方式二:while
aTuple=('b','c','d','e','f','g')
i=0
while i < len(aTuple):
print(aTuple[i])
i=i+1
字典
字典的格式
格式
变量名={key1:value,key2:value,,,}
案例
info = {"name":"an","age":12,"sex":"男"}
字典的每个元素由2部分组成,键(key):值(value)
根据键访问值
案例:有对应key的
info = {"name":"an","age":18,"sex":"男"}
print(info["name"])
#an
案例:无对应key的
info = {"name":"an","age":12,"sex":"男"}
print(info["name12"])
#KeyError: 'name12'
思考:假如我们不确定字典中是否存在某个键而又想获取其值时,如何操作?
案例:有对应key的
info = {"name":"an","age":12,"sex":"男"}
print(info.get("name"))
#an
案例:无对应key的
info = {"name":"an","age":12,"sex":"男"}
print(info.get("name"))
#None
案例:无对应key的,默认返回数据
info = {"name":"an","age":12,"sex":"男"}
print(info.get("name12","无数据"))
#无数据
修改元素
字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改,否则是新增
案例:对应的key
info = {"name":"an","age":12,"sex":"男"}
info["age"] =14
print(info)
#{'name': 'anfly', 'age': 14, 'sex': '男'}
无对应的key
info = {"name":"an","age":12,"sex":"男"}
info["gender"] ="属鸡"
print(info)
#{'name': 'anfly', 'age': 12, 'sex': '男', 'gender': '属鸡'}
有对应的key则是修改数据,没有对应的key是新增数据
添加元素
info = {"name":"an","age":12,"sex":"男"}
info["gender"] ="属鸡"
print(info)
#{'name': 'anfly', 'age': 12, 'sex': '男', 'gender': '属鸡'}
删除元素
del,clear() ---- 清空
del (删除指定的元素)
删除整个字典
info = {"name":"an","age":12,"sex":"男"}
del info
print(info)
#NameError: name 'info' is not defined
删除某个元素
info = {"name":"an","age":12,"sex":"男"}
del info["name"]
print(info)
#{'age': 12, 'sex': '男'}
clear清空
info = {"name":"an","age":12,"sex":"男"}
info.clear()
print(info)
#{}
查询长度
len():查询键值对的个数
info = {"name":"an","age":12,"sex":"男"}
print(len(info))
#3
字典中循环
取出字典中的key
info = {"name":"an","age":12,"sex":"男"}
for i in info.keys():
print(i)
结果:name age sex
案例:取出字典中的value
info = {"name":"an","age":12,"sex":"男"}
for i in info.values():
print(i)
结果:an 12 男
取出字典中的key和value
info = {"name":"an","age":12,"sex":"男"}
for i in info.keys():
print(i,info[i])
方式二:
info = {"name":"an","age":12,"sex":"男"}
for k,v in info.items():
print(k,v)
如何实现带下标索引的遍历?
for i in 可迭代:
print(i)
enumerate()实现索引的遍历
names=["anfly","tom","Meachal"]
for i,chr in enumerate(names):
print(i,chr)
返回值
0 anfly
1 tom
2 Meachal