Average acquisition question

Asked 2 years ago, Updated 2 years ago, 17 views

text=input" (enter a word):")
result=text.split()
total_length=sum(len(result))
average_length= total_length/len(list)
print ('average length:', average_length)

I made it like this to solve the average problem, but when I looked up the error "int' object is not usable" and looked it up, the error that the list value is not sum appears, so what should I use other than sum to keep adding the list?len(result[0])+..I can't do len(result[n]) right? I'm a little at a loss because I don't know any functions since I learned Python a few days ago.

python

2022-09-21 10:23

2 Answers

Are you wanted something like this

sentence = input()  # 'i am a student'
word = sentence.split()  # ['i', 'am', 'a', 'student']
word_len = [len(w) for w in word]  # [1, 2, 1, 7]
mean_word_len = sum(word_len) / len(word_len)  # 11 / 4
print(mean_word_len)  # 2.75

To receive a sentence, the word must be separated by space.
A code that calculates the average length of words in a sentence.


2022-09-21 10:23

The len function returns length when used for data types such as list, tuple, string.
That is, returns a number.
The sum function is a function that obtains the sum when elements of a data type such as list or tuple are numeric (for example, sum ([1,2,3]).
This means that it cannot be used with sum(39).
If result = [1, 2, 3], total_length = sum(len(result)) would be the same as total_length = sum(3)
So there's an error.
Means obtained and If you want to continue adding a list of any length, I don't know what it has to do with but please refer to the example below for adding a list.

arr = [1,2,3]
arr2 = [7,8]
arr.extend(arr2)
print(arr)  # [1,2,3,7,8]


2022-09-21 10:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.