计算平均字长的程序出现问题

Issue with program that counts the average word length

我是 Python 的新手,所以我只熟悉一些非常基本的函数,我正在做一个循环练习。我需要构建一个计算平均字长的程序。这是我的代码:

sentence = input ("Give your sentence:")
words = len(sentence.split())
print(words)
characters = 0
for word in words:
    characters += len(word)
    average_word_lengt = characters/words

给我一个错误:

'int' object is not iterable

这是什么意思,我怎样才能让它发挥作用?

主要问题:

下面声明returnswords为整数。因此你不能迭代。

words = len(sentence.split())

如果您想遍历单词列表,请试试这个:

words = sentence.split()
n_words = len(words)

更详细:

这是您的代码的更新版本和工作版本,使用上面的示例:

sentence = input("Give your sentence: ")
# Updated here -->
words = sentence.split()
n_words = len(words)
# <--
print(words)
characters = 0
for word in words:
    characters += len(word)
    average_word_length = characters/n_words  # <-- and here.

如果您想使用称为 list comprehension 的语法更进一步(这非常有用!),这是另一个示例:

words = input("Give your sentence: ").split()
avg_len = sum([len(w) for w in words])/len(words)

print('Words:', words)
print('Average length:', avg_len)

你不能迭代长度。我想您需要先获取所有字符串 len;求和然后取平均值

import functools

sentence = input("Give your sentence:")
word_lens = list(map(lambda x: len(x), sentence.split()))
sums = functools.reduce(lambda x, y: x + y, word_lens, 0)
print(round(sums / len(word_lens)))

sentence = input("Give your sentence:")
word_lens = list(map(lambda x: len(x), sentence.split()))
sums = 0
for l in word_lens:
    sums += l
print(round(sums / len(word_lens)))

你可以直接迭代字符串

sentence = input ("Give your sentence:")
word_count = {} #dictionary to store the word count
for word in sentence:
    if word in word_count.items(): #check if word is in the dictionary
        word_count[word] +=1 #adds +1 if already is
    else:
        word_count[word] = 1 #adds the word on the dict
result=len(sentence)/len(word_count) #this will divide the total characters with total single characters
print(result)