Python字符计数程序报IndexError,请求问题排查
字符统计程序的问题排查与修复
问题概述
刚学完Python基础,正在做字符统计任务:用字母列表统计句子中对应字符的数量。当前程序存在两个问题:
- 计数异常(比如句子里只有1个
c,却统计出30) - 运行到字符
c时抛出索引错误:
File "/home/pi/main.py", line 17, in <module> if statementLower[l] == alphabet[m]: IndexError: string index out of range
当前输出仅:
a:44 b:20 c:30
随后触发上述错误。
原代码
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] statement = "This is my task I want to complete. But I am stuck!!!!!!" statementLower = statement.lower() m = 0 l=0 count = 0 print(statementLower) for i in alphabet: frequency = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #print("i for alphabet") #print("-" + i + "-") for k in statementLower: #print("k statement Lower") #print(k) if statementLower[l] == alphabet[m]: #print(count) count = count+1 frequency[m] = count l+l+1 continue else: #print("else continue loop") l=l+1 continue if frequency[m] != 0: #print("frequency loop") print(str(alphabet[m]+ ":" + str(frequency[m]))) m=m+1 count = 0 l=0 continue
错误原因分析
- 索引越界:
内层循环遍历整个字符串时,手动用l递增索引,遍历完一轮后l等于字符串长度。且只有当字母存在时才重置l=0,若字母不存在,l不会重置,下一轮统计时statementLower[l]必然超出索引范围。 - 计数逻辑混乱:
l+l+1是无效语句,应该写成l += 1,导致匹配到目标字符时l不递增,重复统计同一个位置的字符,造成计数异常。- 外层循环遍历
alphabet元素,却用m控制当前统计字母,逻辑冗余;内层判断应该直接用当前遍历的i,而非alphabet[m]。 frequency数组完全多余,单个变量即可记录当前字母计数。
修复后的代码
基础遍历版
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] statement = "This is my task I want to complete. But I am stuck!!!!!!" statementLower = statement.lower() for char in alphabet: count = 0 for s_char in statementLower: if s_char == char: count += 1 if count > 0: print(f"{char}: {count}")
简洁版(用内置count()方法)
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] statement = "This is my task I want to complete. But I am stuck!!!!!!" statementLower = statement.lower() for char in alphabet: count = statementLower.count(char) if count > 0: print(f"{char}: {count}")
正确输出
a: 4 b: 1 c: 1 e: 3 h: 1 i: 4 k: 2 m: 2 n: 1 o: 3 p: 1 s: 3 t: 5 u: 2 w: 1 y: 1
内容的提问来源于stack exchange,提问作者seb
相关产品推荐
相关产品推荐

