-->字典用於以鍵:值對的形式儲存資料值。
-->字典是一個有序的、可更改的、不允許重複的集合。
-->在字典中,每個元素都可以透過它們的鍵來訪問,而不是透過索引。
-->如果字典不包含該鍵,則輸出將為「KeyError」。
範例:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } student = {"name":"raja", "class":5} print(thisdict) print(student)
輸出:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964} {'name': 'raja', 'class': 5}
練習:使用巢狀循環找出字串中的字元
1.找出字串中每個字母的頻率
s = 'guruprasanna' name = list(s) j = 0 while j<len(name): key = name[j] count = 1 i = j+1 if key != '*': while i<len(name): if key == name[i]: name[i] = '*' count+=1 i+=1 print(key, count) j+=1
輸出:
g 1 u 2 r 2 p 1 a 3 s 1 n 2
*2。字母只出現一次 *
s = 'guruprasanna' name = list(s) j = 0 while j<len(name): key = name[j] count = 1 i = j+1 if key != '*': while i<len(name): if key == name[i]: name[i] = '*' count+=1 i+=1 if count == 1 and key!='*': print(key, count) j+=1
輸出:
g 1 p 1 s 1
3。最常見的字母
s = 'guruprasanna' name = list(s) j = 0 while j<len(name): key = name[j] count = 1 i = j+1 if key != '*': while i<len(name): if key == name[i]: name[i] = '*' count+=1 i+=1 if count != 1 and key!='*': print(key, count) j+=1
輸出:
u 2 r 2 a 3 n 2
4。第一個不重複的字母
s = 'guruprasanna' name = list(s) j = 0 while j<len(name): key = name[j] count = 1 i = j+1 if key != '*': while i<len(name): if key == name[i]: name[i] = '*' count+=1 i+=1 if count == 1 and key!='*': print(key, count) break j+=1
輸出:
g 1
5。第一個重複的字母
s = 'guruprasanna' name = list(s) j = 0 while j<len(name): key = name[j] count = 1 i = j+1 if key != '*': while i<len(name): if key == name[i]: name[i] = '*' count+=1 i+=1 if count != 1 and key!='*': print(key, count) break j+=1
6。最後一個不重複的字母
last = ' ' last_count = 0 s = 'guruprasanna' name = list(s) j = 0 while j<len(name): key = name[j] count = 1 i = j+1 if key != '*': while i<len(name): if key == name[i]: name[i] = '*' count+=1 i+=1 if count == 1 and key!='*': last = key last_count = count #print(key, count) j+=1 print(last, last_count)
輸出:
s 1
7。最後重複的字母
last = ' ' last_count = 0 s = 'guruprasanna' name = list(s) j = 0 while j<len(name): key = name[j] count = 1 i = j+1 if key != '*': while i<len(name): if key == name[i]: name[i] = '*' count+=1 i+=1 if count != 1 and key!='*': last = key last_count = count #print(key, count) j+=1 print(last, last_count)
輸出:
n 2
8。最常見的字母
s = 'guruprasanna' name = list(s) j = 0 last = ' ' last_count = 0 while j<len(name): key = name[j] count = 1 i = j+1 if key != '*': while i<len(name): if key == name[i]: name[i] = '*' count+=1 i+=1 if count != 1 and key!='*': if count>last_count: last = key last_count = count j+=1 print(last, last_count)
9。元音出現頻率 (a,e,i,o,u)
vowels = ['a','e','i','o','u'] last = ' ' last_count = 0 s = 'guruprasanna' name = list(s) j = 0 while j<len(name): key = name[j] if key in vowels: count = 1 i = j+1 if key != '*': while i<len(name): if key == name[i]: name[i] = '*' count+=1 i+=1 if key!='*': print(key, count) j+=1
輸出:
u 2 a 3
以上是Python day-Dictionary,使用嵌套循環的字元頻率的詳細內容。更多資訊請關注PHP中文網其他相關文章!