1. 程式人生 > 實用技巧 >資料型別-元組&字典

資料型別-元組&字典

一、元組: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