元组
1.格式:
t=(元素,元素)
2.特点:
有序,可重复,不可变,任意类型
3.访问元组
索引值存在:print(t[2])
索引值不存在:报错
4.查询:
1.查询个数:t.count(元素
2.查询下标:t.index(元素)
5.修改:
不可修改,虚转换类型
6.类型转换
1)列表转换元祖
例如:
aa = [23,34,45,56,67]
a=tuple(aa)
print(a)
2)元组转换列表
aTuple=('b','c','d','e','f','g')
a = list(aTuple)
print(a)
7.元组的循环取值
1)for循环
for i in aTuple:
print(i)
2)while循环
i=0
while i < len(aTuple):
print(aTuple[i])
i=i+1
字典
1.格式:
变量名 = {key1:value,key2:value,,,}
列如:info = { "name" : "gdl", "age" : 12 , "sex" : "男" }
2.根据key 访问value:(3种)
1) info = { "name" : "gdl", "age" : 12 , "sex" : "男" }
print(info["name"])
2) info = { "name" : "gdl", "age" : 12 , "sex" : "男" }
print(info.get("name"))
【没有时返回None】
3)info = { "name" : "gdl", "age" : 12 , "sex" : "男" }
print(info.get("name12","无数据"))
【没有时返回‘无数据’】
3.修改元素:
info = { "name" : "gdl", "age" : 12 , "sex" : "男" }
info["age"] = 14
print(info) # 14
4.添加元素:
info = { "name" : "gdl", "age" : 12 , "sex" : "男" }
info["address"] = "北京"
print(info)
总结:有对应的key则是修改数据,没有对应的key是新增数据
5.删除元素:(2种)
del (删除指定的元素)
1) info={"name":"anfly","age":12,"sex":"男"}
del info
print(info) 【删除完,报错显示name 'info' is not defined】
2) info={"name":"anfly","age":12,"sex":"男"}
del info["name"]
print(info) 【删除某个元素】
clear清空
1) info={"name":"anfly","age":12,"sex":"男"}
info.clear()
print(info)【删除完,显示{}】
6.查询长度:
len():查询键值对的个数
info={"name":"anfly","age":12,"sex":"男"}
print(len(info))
7. 字典中循环:
取出字典中的key
info={"name":"anfly","age":12,"sex":"男"}
for i in info.keys():
print(i)
取出字典中的value
info={"name":"anfly","age":12,"sex":"男"}
for i in info.values():
print(i)
取出字典中的key和value
1) info={"name":"gdl","age":12,"sex":"男"}
for i in info.keys():
print(i,info[i])
2) info={"name":"gdl","age":12,"sex":"男"}
for k,v in info.items():
print(k,v)
enumerate()实现索引的遍历
names = ["gdl","jack","rose"]
for i,chr in enumerate(names):
print(i,chr)
结果:0 gdl
1 jack
2 rose