1.元组
格式:aTuple=(23,35,56,34,11,21)
访问元组,通过索引取数据
aTuple=(23,35,56,34,11,21)
print(aTuple[2])
#56
查询个数
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')
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
2.字典
字典的格式
变量名={key1:value,key2:value,,,}
字典的每个元素由2部分组成,键(key):值(value)
根据键访问值
info = {"name":"jack","age":12,"sex":"男"}
print(info["name"])
#jack
修改元素
字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改,否则是新增
info = {"name":"jack","age":12,"sex":"男"}
info["age"] =14
print(info)
#{'name': 'jack', 'age': 14, 'sex': '男'}
添加元素
info = {"name":"jack","age":12,"sex":"男"}
info["gender"] ="属鸡"
print(info)
#{'name': 'jack', 'age': 12, 'sex': '男', 'gender': '属鸡'}
删除元素
del,clear() ---- 清空
删除指定的元素
删除整个字典
info = {"name":"jack","age":12,"sex":"男"}
del info
print(info)
#NameError: name 'info' is not defined
删除某个元素
info = {"name":"jack","age":12,"sex":"男"}
del info["name"]
print(info)
#{'age': 12, 'sex': '男'}
查询长度
len():查询键值对的个数
info = {"name":"jack","age":12,"sex":"男"}
print(len(info))
#3
字典中循环
取出字典中的key
info = {"name":"jack","age":12,"sex":"男"}
for i in info.keys():
print(i)
取出字典中的value
info = {"name":"jack","age":12,"sex":"男"}
for i in info.values():
print(i)
取出字典中的key和value
方式一:
info = {"name":"jack","age":12,"sex":"男"}
for i in info.keys():
print(i,info[i])
方式二:
info = {"name":"jack","age":12,"sex":"男"}
for k,v in info.items():
print(k,v)
enumerate()实现索引的遍历
names=["jack","tom","Meachal"]
for i,chr in enumerate(names):
print(i,chr)