You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用for循环统计字母频率的问题求助

字符串字母计数代码修复方案

需要用for循环和if语句统计给定字符串中每个字母的出现次数,对应的伪代码如下:

for every letter in the alphabet list:
    Create a variable to store the frequency of each letter in the string and assign it an initial value of zero
    for every letter in the given string:
        if the letter in the string is the same as the letter in the alphabet list
            increase the value of the frequency variable by one.
    if the value of the frequency variable does not equal zero:
        print the letter in the alphabet list followed by a colon and the value of the frequency variable

用户编写的代码如下,但无法得到正确计数结果:

quote =  "I watched in awe as I saw her swim across the ocean."

xquote= quote.lower()
print(xquote)

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"]
for i in alphabet:
  c_alphabet= {"a": 0, "b":0, "c":0, "d":0,"e":0,"f":0,"g":0,"h":0,"i":0,"j":0,"k":0,"l":0,"m":0,"n":0,"o":0,"p":0,"q":0,"r":0,"s":0,"t":0,"u":0,"v":0,"w":0,"x":0,"y":0,"z":0}
  for i in xquote:
    if i == alphabet:
      c_alphabet[i]+=1
print(c_alphabet)

问题分析

  • 字典重复初始化:c_alphabet被放在外层for i in alphabet循环内,每次循环都会重置为全0字典,最后仅保留最后一次循环的空计数结果
  • 变量名冲突:外层循环用i表示字母表中的字母,内层循环又用i遍历字符串,直接覆盖了外层变量,导致逻辑混乱
  • 错误的判断条件:if i == alphabet是拿单个字符和整个字母列表做比较,永远为False,计数根本不会增加
  • 打印时机错误:print(c_alphabet)放在所有循环外,只会输出最后一次循环后的字典,而非完整统计结果

修正后的代码

方案一(更高效的实现)

quote = "I watched in awe as I saw her swim across the ocean."
xquote = quote.lower()

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"]
c_alphabet = {letter: 0 for letter in alphabet}  # 仅初始化一次字典

# 遍历字符串统计字母次数
for char in xquote:
    if char in c_alphabet:  # 判断当前字符是否为字母
        c_alphabet[char] += 1

# 输出非零计数结果
print("c_alphabet = {")
for letter, count in c_alphabet.items():
    if count != 0:
        print(f"    '{letter}': {count},")
print("}")

方案二(严格遵循伪代码嵌套逻辑)

quote = "I watched in awe as I saw her swim across the ocean."
xquote = quote.lower()

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"]
c_alphabet = {}

for letter in alphabet:
    count = 0
    for char in xquote:
        if char == letter:
            count += 1
    if count > 0:
        c_alphabet[letter] = count

print(f"c_alphabet = {c_alphabet}")

输出结果示例

c_alphabet = {'a': 6, 'c': 2, 'd': 1, 'e': 4, 'g': 1, 'h': 3, 'i': 3, 'm': 1, 'n': 2, 'o': 2, 'r': 2, 's': 4, 't': 2, 'w': 3}

内容的提问来源于stack exchange,提问作者Lucky B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 09:01:21