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

Python统计列表内特定字符数量出错,求代码调试帮助

问题原因

你代码里的判断逻辑出错了:if str('a') in array 是在整个列表中检测是否存在'a',而非判断当前循环的元素是不是'a'。因为你的列表里确实包含'a',所以每一次循环这个条件都会成立,最终sum_of_as累加的是列表的总长度,而非'a'的实际数量。

修正代码
array = ['a', 'b', 'c', 'a']
sum_of_as = 0
for i in array:
    if i == 'a':  # 改为判断当前元素是否等于目标字符
        sum_of_as += 1
        
print(f'''The number of a's in this array are {sum_of_as}''')
更高效的写法

Python列表自带count()方法,能直接统计指定元素的出现次数,无需手动编写循环:

array = ['a', 'b', 'c', 'a']
sum_of_as = array.count('a')
print(f'''The number of a's in this array are {sum_of_as}''')

内容的提问来源于stack exchange,提问作者Stergios Katseas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:31:04