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

Python中如何累加数组内字符串的字符总数以计算平均值?

解决字符串数组字符总数累加及后续任务实现问题

首先解决你遇到的字符总数累加问题:

  • 你之前尝试的sum方法报错,是因为直接对字符串数组求和(sum(Words))会触发类型错误,Python无法直接相加字符串;而""join(Words)是把所有单词拼接成一个长字符串,如果你用len("".join(Words))是可以得到总字符数的,但更高效直观的方式是直接对每个单词的长度求和:
total_chars = sum(len(word) for word in Words)

这个生成器表达式会遍历Words数组里的每个单词,计算其长度后累加,得到所有字符的总数。

接下来完成整个任务的剩余部分:统计每个单词字符数、计算平均值、判断阅读水平。以下是完整的代码实现(假设阅读水平判断规则为:平均字符数≤3 → junior,4-6 → middle,≥7 → senior,你可以根据实际要求调整):

WordCount = 0

# 单词数量验证
WordCount = int(input("How many words are in this sentence? :"))
while WordCount < 1 or WordCount > 20:
    print("Up to 20 words are allowed, please try again.")
    WordCount = int(input("How many words are in this sentence? :"))

Words = [""] * WordCount
for i in range(WordCount):
    Words[i] = input("Please enter each word :")

# 统计每个单词的字符数并打印
print("\n每个单词的字符数:")
for word in Words:
    print(f"{word}: {len(word)}")

# 计算总字符数和平均值
total_chars = sum(len(word) for word in Words)
average = total_chars / WordCount

# 判断阅读水平
if average <= 3:
    level = "junior"
elif 4 <= average <= 6:
    level = "middle"
else:
    level = "senior"

print(f"\n总字符数:{total_chars}")
print(f"平均字符数:{average:.2f}")
print(f"阅读水平:{level}")

关键说明:

  • sum(len(word) for word in Words):通过生成器表达式高效计算总字符数,避免了拼接长字符串的额外内存开销
  • 统计每个单词字符数时,直接遍历数组中的每个单词调用len()即可
  • 平均值计算后用:.2f格式化保留两位小数,结果更直观
  • 阅读水平的判断条件可根据任务要求自行修改阈值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 07:58:19