Python计算句子单词平均长度的代码纠错求助
问题需求
给定由一个或多个空格分隔单词组成的字符串,计算所有单词的平均长度。
平均单词长度计算公式:平均单词长度 = 单词总字符数(不含空格) / 单词总数量。
原有实现代码运行结果不符合预期,错误代码如下:
sentence = input("sentence: ") words = sentence.split() total_number_of_characters = 0 number_of_words = 0 for word in words: total_number_of_characters += len(sentence) number_of_words += len(words) average_word_length = total_number_of_characters / number_of_words print(average_word_length)
错误原因排查
循环逻辑存在两处核心错误:
- 总字符数统计逻辑错误:遍历单个单词时,累加的是整个输入字符串的长度
len(sentence),而非当前遍历到的单词长度len(word),导致总字符数计算结果远大于实际值。 - 单词总数统计逻辑错误:
sentence.split()执行完成后,可直接通过len(words)拿到拆分后的单词总数。原有代码在遍历每个单词时反复累加整个单词列表的长度len(words),最终统计的单词数是实际值的「单词数」倍,结果完全失真。
修正方案
方案1:保留遍历逻辑的修正版本
sentence = input("sentence: ") words = sentence.split() total_number_of_characters = 0 # 直接获取单词总数,无需循环累加 number_of_words = len(words) for word in words: # 仅累加当前遍历单词的长度 total_number_of_characters += len(word) average_word_length = total_number_of_characters / number_of_words print(average_word_length)
方案2:精简实现版本
利用内置函数直接计算总字符数,代码更简洁:
sentence = input("sentence: ") words = sentence.split() average_word_length = sum(len(word) for word in words) / len(words) print(average_word_length)
题目已明确输入为一个或多个空格分隔的字符串,无需额外处理拆分后空列表导致的除零异常。
内容的提问来源于stack exchange,提问作者user19401771
相关产品推荐
相关产品推荐

