【问题标题】:Average of words in a sentence?一个句子中单词的平均数?
【发布时间】:2014-11-04 23:45:25
【问题描述】:
print 'The average amount of words in the sentence is' ,average, 'words'

我只是无法让它工作

【问题讨论】:

  • 首先,你有一个for word in words: 循环,但你没有对word 做任何事情。你为什么打电话给len(words),而不是打电话给len(word)
  • 第二,为了求平均,你必须把它们加起来。您可以在进行过程中保持一个运行总数,或者您可以将它们粘贴在一个列表中,稍后再致电sum,或者您可以想到的任何其他事情,但您必须做一些事情
  • 然后,一旦你有了这个总数,你只需要把它除以字数,你就得到了平均值。完成全部工作后,您应该能够弄清楚如何做到这一点。
  • 想想平均值的数学定义 - 单个值的总和除以值的数量。在这种情况下,“值”是每个单词的长度。
  • 能否请你们重新编写能够计算列表中每个单词数量的实际形式,然后将每个字母数量相加成平均值。我很新,所以我为看起来很粗糙的代码道歉。

标签: python list split


【解决方案1】:

您应该将各个字符相加并除以列表中的单词数。

单词按空格分隔(但您应该考虑不同的场景)。 nbrChar 是用于计算所有单词中字符数的变量。

from __future__ import division
sentence = raw_input ("Please write a sentence for it to be counted and averaged:")

words = sentence.split(" ") #You should split words by space

nbrChar, average=0, .0

for word in words:
    nbrChar+= len(word)

average= nbrChar // len(words) 

print 'The average amount of words in the sentence is' ,average, 'words'

【讨论】:

    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多