一、元组:tuple
作用:存多个值,对比列表来说,元组不可变(是可以当做字典的key的),主要是用来读取,不可以修改。
#定义:与列表类型对比,只不过[]换成()。即中括号换成小括号
info_of_sean = ('sean',18,'70kg','175cm')
print(type(info_of_sean)) #tuple
info_of_sean = ['sean',18,'70kg','175cm']
print(type(info_of_sean)) # list
二、tuple 优先掌握的操作应用
2.1按索引取值(正向取+反向取):只能取
print(info_of_sean[0][2]) #返回:a
print(info_of_sean[-1]) #返回:175cm
2.2切片(顾头不顾尾,步长)(开始,终止,步长)
res = info_of_sean[0:2:1]
print(res) #sean 18
info_of_sean[1]=25 #报错,元组不支持改变
2.3长度Len
info_of_sean = ('sean',18,'70kg','175cm')
print(len(info_of_sean)) # 4
2.4成员运算in和not in
msg = 'sean' in info_of_sean
print(msg)
msg = 'sean' not in info_of_sean
print(msg)
2.5循环
for i in info_of_sean:
print(i) #返回:sean 18 70kg 175cm
三、字典dic
作用:存多个值,key-value存取,取值速度快
定义:key必须是不可变类型,value可以是任意类型
info={'name':'egon','age':18,'sex':'male'} #本质info=dict({....})
或
info=dict(name='egon',age=18,sex='male')
或
info=dict([['name','egon'],('age',18)])
或
{}.fromkeys(('name','age','sex'),None)
四、字典优先掌握的操作应用
info_of_sean = {'name':'sean','age':18,'weight':'70kg','height':'175cm'}
print(type(info_of_sean)) #dict
4.1按key存取值:可存可取
print(info_of_sean['name']) #按key取值
info_of_sean['name']='egon' #按key修改
print(info_of_sean) #返回:{'name': 'egon', 'age': 18, 'weight': '70kg', 'height': '175cm'}
*key不存在则加元素,存在则改值*
info_of_sean['gender'] = 'male'
print(info_of_sean) #{'name': 'sean', 'age': 18, 'weight': '70kg', 'height': '175cm', 'gender': 'male'}
*取值使用get(key)字典中使用*
dic = info_of_sean.get('name')
print(dic)
4.2长度len
info_of_sean = {'name':'sean','age':18,'weight':'70kg','height':'175cm'}
print(len(info_of_sean)) #返回 4
4.3成员运算in和not in
res = 'name' in info_of_sean #key作为判断in或not in的依据
print(res) # TRUE
4.4删除
del info_of_sean['name'] #万能删除,按key删除
print(info_of_sean) #{'age': 18, 'weight': '70kg', 'height': '175cm'}
info_of_sean.pop('age') #pop指定key删除
print(info_of_sean) #{'weight': '70kg', 'height': '175cm'}
4.5对于Dict,索引找不到的,则会默认在末尾增加。如需增加也可以通过setdefault增加,setdefault(key,value)
dic={'age':18}
res = dic.setdefault('name',"SEAN")
print(dic) #{'age': 18, 'name': 'SEAN'}
print(res) #SEAN
sean=dic.setdefault('gentle','male')
print(sean) #male
print(dic) #{'age': 18, 'name': 'SEAN', 'gentle': 'male'}
4.6循环
for i in info_of_sean:
print(i) #返回key
dic = {'name':'sean','age':18,'gentle':'male'}
for k in dic.keys():
print(k)
dic = {'name':'sean','age':18,'gentle':'male'}
print(list(dic.keys()))
dic = {'name':'sean','age':18,'gentle':'male'}
for v in dic.values():
print(v) #返回value值
dic = {'name':'sean','age':18,'gentle':'male'}
for k,v in dic.items():
print(k,v) #返回key value