访问元组
通过·索引取数据:
aTuple=(23,35,56,34,11,21)
print(aTuple[2])
索引值存在:#56
索引值不存在:报错
查询个数
count查询出现个数
aTuple=('b','c','d','e','f','g')
print(aTuple.count('d'))
#1
查询索引
aTuple=('b','c','d','e','f','g')
print(aTuple.index('d',0,4))
有对应元素:#2
无对应元素:报错
列表转元组
aa=[23,34,45,56,67]
cc=tuple(aa)
print(cc)
#(23, 34, 45, 56, 67)
元组转列表
bb=("b","c","d","f","g")
a=list(bb)
print(a)
#['b', 'c', 'd', 'e', 'f', 'g']
元组循环取值
aa=[22,45,58,90]
for i in aa:
print(i)
#[22,45,58,90]
while循环:
aa=[22,45,58,90]
i=0
while i<len(aa):
print(aa[i])
i+=1
字典
根据键访问值
info = {"name":"111","age":18,"sex":"男"}
有对应的key
print(info["name"])
#111
无对应的key:报错
不确定字典中是否存在某个键而又想获取其值时,如何操作?
有对应key的
info = {"name":"111","age":12,"sex":"男"}
print(info.get("name"))
#111
无对应key的
info = {"name":"anfly","age":12,"sex":"男"}
print(info.get("name"))
#None
无对应key的,默认返回数据
info = {"name":"anfly","age":12,"sex":"男"}
print(info.get("name12","无数据"))
#无数据
修改元素:
字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改,否则是新增
对应的key
info = {"name":"anfly","age":12,"sex":"男"}
info["age"] =14
print(info)
#{'name': 'anfly', 'age': 14, 'sex': '男'}
无对应的key
info = {"name":"anfly","age":12,"sex":"男"}
info["gender"] ="属鸡"
print(info)
#{'name': 'anfly', 'age': 12, 'sex': '男', 'gender': '属鸡'}
添加元素:
info = {"name":"anfly","age":12,"sex":"男"}
info["gender"] ="属鸡"
print(info)
#{'name': 'anfly', 'age': 12, 'sex': '男', 'gender': '属鸡'}
删除元素:
删除整个字典
info = {"name":"anfly","age":12,"sex":"男"}
del info
print(info)
#NameError: name 'info' is not defined
删除某个元素
info = {"name":"anfly","age":12,"sex":"男"}
del info["name"]
print(info)
#{'age': 12, 'sex': '男'}
清空:
info = {"name":"anfly","age":12,"sex":"男"}
info.clear()
print(info)
#{}
查询长度:
info = {"name":"anfly","age":12,"sex":"男"}
print(len(info))
#3
字典中的循环:
取出字典中的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():
rint(i)
取出字典中的key和value
方法一:
info = {"name":"anfly","age":12,"sex":"男"}
for i in info.keys():
print(i,info[i])
方法二:
info = {"name":"anfly","age":12,"sex":"男"}
for k,v in info.items():
print(k,v)
enumerate()实现索引的遍历:
names=["anfly","tom","Meachal"]
for i,chr in enumerate(names):
print(i,chr)