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)
逻辑说明
- 用
split()将原字符串按空格分割为单词列表 - 遍历列表中的每个单词,检查其长度是否小于5
- 每找到一个符合条件的单词,计数器
count加1 - 最后输出统计得到的整数结果
内容的提问来源于stack exchange,提问作者Ruby
相关产品推荐
相关产品推荐

