-->字典用于以键:值对的形式存储数据值。
-->字典是一个有序的、可更改的、不允许重复的集合。
-->在字典中,每个元素都可以通过它们的键来访问,而不是通过索引。
-->如果字典不包含该键,则输出将为“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中文网其他相关文章!