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

Python仅用for循环统计字符串单词出现次数及缩进问题修正

词频统计代码缩进错误修复

需求与问题

  • 实现目标:编写Python代码统计字符串中每个单词的出现次数,仅允许使用for循环实现,禁止使用集合、字典等内置数据类型
  • 故障现象:代码存在缩进错误,无法输出正确的统计结果
  • 原始错误代码:
mystring="Virat plays cricket. Virat is a batsman."
mylist=mystring.split(' ')
j=0
#the i outer loop that will iterate each element in list
for i in range(0,len(mylist)):
count=1
'''the j loop is to check whether value at j has occurred previously or not,
Like Virat at index 3 has occured previously also at index 0, so it should
not count that and it should break the loop because virat has counted previously
'''
for j in range(i-1,-1,-1):
    if mylist[i]==mylist[j]:
        break
if j==-1:
      '''if a word hasn't founded previously then it should start iterating
      next element from mylist[i]'''
      for j in range(i+1,len(mylist)):
        if mylist[i]==mylist[j]:
          count=count+1
print(mylist[i]," has occured ",count)

错误原因

Python使用缩进判定代码块归属,原代码缩进逻辑完全混乱:

  • 外层遍历索引i的for循环下,所有从属逻辑(计数变量初始化、前置重复校验、后置次数统计、结果打印)都没有缩进至循环作用域内,循环根本不会执行这部分逻辑
  • 前置重复校验的判断分支、结果打印语句缩进层级错误,和所属逻辑块不在同一层级,会触发重复打印、计数错误等问题

修正后可运行代码

mystring = "Virat plays cricket. Virat is a batsman."
mylist = mystring.split(' ')
j = 0
# 外层i循环遍历列表中每个元素
for i in range(0, len(mylist)):
    count = 1
    # j反向循环检查当前i位置的单词是否在之前的位置出现过
    # 例如下标3位置的Virat之前在下标0已经出现过,直接中断循环不重复计数
    for j in range(i-1, -1, -1):
        if mylist[i] == mylist[j]:
            break
    # j==-1说明反向遍历完所有前置元素都没找到重复,是第一次出现该单词
    if j == -1:
        # 从i的下一个位置开始往后遍历,统计该单词总出现次数
        for j in range(i+1, len(mylist)):
            if mylist[i] == mylist[j]:
                count = count + 1
        print(mylist[i], " has occured ", count)

运行输出

Virat  has occured  2
plays  has occured  1
cricket.  has occured  1
is  has occured  1
a  has occured  1
batsman.  has occured  1

注:当前实现严格遵守限制,未使用字典、集合等禁止的内置数据类型,仅通过多层for循环完成去重和计数逻辑。

内容的提问来源于stack exchange,提问作者Rohit Kaushik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 10:24:22