字典、列表、元祖、字符串的综合(1)
生活随笔
收集整理的這篇文章主要介紹了
字典、列表、元祖、字符串的综合(1)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.字典擁有keys方法,例如:
h = {'t':1,'a':2,'o':3,'r':4} print(type(h.keys())) #輸出結(jié)果為: #<class 'dict_keys'>如果要使用列表方法要先用list()將其轉(zhuǎn)換為列表類(lèi)型2.字典的setdefault和get方法的應(yīng)用——統(tǒng)計(jì)一個(gè)字符串中各字母出現(xiàn)的次數(shù)
def counts(index):dict_crea = {}for i in index:dict_crea.setdefault(i,0)dict_crea[i] += 1return dict_crea index = "This is a test" print(counts(index)) #輸出結(jié)果為: #{'T': 1, 'h': 1, 'i': 2, 's': 3, ' ': 3, 'a': 1, 't': 2, 'e': 1}setdefault原理:若字典內(nèi)部有名為i的鍵,則什么操作也不會(huì)做,否則執(zhí)行dict_crea[i] = 0
for循環(huán)內(nèi)部也可以換成: dict_crea[i] = dict_crea.get(i,0) + 1get原理:若字典內(nèi)部有名為i的鍵,則返回該鍵所映射的值,否則返回0
3.字典的鍵
python的字典是基于散列表(Hash table)實(shí)現(xiàn)的,也就是鍵必須是可散列的,即hashable
Python中,整形,浮點(diǎn)型,字符型等不可變數(shù)據(jù)類(lèi)型是可散列的,列表和字典等可變類(lèi)型是不可散列的。
即列表和字典不能作為字典的鍵。例如:
dict_crea = {} lists = ['1','2'] dict_crea[lists] = 5 #會(huì)彈出錯(cuò)誤信息如下: TypeError: unhashable type: 'list'4.str.count(sub,start,end)
用于統(tǒng)計(jì)sub字符在str從start——end范圍內(nèi)出現(xiàn)的次數(shù)
start,end均指下標(biāo),且不包含end,start默認(rèn)為0,end默認(rèn)為字符串長(zhǎng)度
例如:
s = 'This is a test for the function count,the result is:' sub = 'T' sub2 = 'is' print(s.count(sub,0,1)) print(s.count(sub2,2,3)) print(s.count(sub2,2,4)) #輸出結(jié)果為: 1 0 1
總結(jié)
以上是生活随笔為你收集整理的字典、列表、元祖、字符串的综合(1)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python的读取纯文本文件的几种模式
- 下一篇: 字典、列表、元祖、字符串的综合(2)