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



我对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

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

主要问题:

以下语句以整数形式返回words。 因此,您无法迭代。

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.

如果你想使用一种叫做列表推导的语法(这非常有用!(更进一步,这里有另一个例子:

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)

你不能迭代长度。我想你需要先得到所有的字符串镜头;获取总和,然后获得平均值

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)

最新更新