Python: How can I calculate the average word length in a sentence using the .split command?

后端 未结 9 1648
甜味超标
甜味超标 2021-01-03 11:40

new to python here. I am trying to write a program that calculate the average word length in a sentence and I have to do it using the .split command. btw im using python 3.2

9条回答
  •  走了就别回头了
    2021-01-03 11:53

    The concise version:

    average = lambda lst: sum(lst)/len(lst) #average = sum of numbers in list / count of numbers in list
    avg = average([len(word) for word in sentence.split()]) #generate a list of lengths of words, and calculate average
    

    The step-by-step version:

    def average(numbers):
        return sum(numbers)/len(numbers)
    sentence = input("Please enter a sentence: ")
    words = sentence.split()
    lengths = [len(word) for word in words]
    print 'Average length:', average(lengths)
    

    Output:

    >>> 
    Please enter a sentence: Hey, what's up?
    Average length: 4
    

提交回复
热议问题