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

Python统计字符串中长度小于5的单词数量求助

修正后的Python代码:统计长度小于5的单词数量

原代码存在两个核心问题:

  • 错误将单词列表words与字符串'1,2,3,4'做相等判断,两者类型、内容完全不匹配,永远无法触发统计逻辑
  • 定义了letterCount字典但未实际利用,也没有遍历单词去判断长度条件

简洁实现版本

text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout."
words = text.split()
count = sum(1 for word in words if len(word) < 5)
print(count)

分步理解版本

text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout."
words = text.split()
count = 0
# 遍历每个单词,判断长度是否小于5
for word in words:
    if len(word) < 5:
        count += 1
print(count)

逻辑说明

  1. 用split()将原字符串按空格分割为单词列表
  2. 遍历列表中的每个单词,检查其长度是否小于5
  3. 每找到一个符合条件的单词,计数器count加1
  4. 最后输出统计得到的整数结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:25:31