user10332249
user10332249

Reputation:

How to get the mean of each index in a list and take the ones that are bigger than average?

I have this list called hello:

['Apple is one of the most healthy fruits ever - it grows in many countries',
 'Jenny likes strawberry',
 'He had an accident in New York Downtown',
 'One of the safest cities is the city Tokyo in Japan',
 'Some drugs are better than others',
 'Ice-cream is famous, Italian ice-cream is the most famous',
 'German cars are known to be the best cars']

I want to have the average characters of these sentences and take the sentences out that is longer than the average. How do I do this?

Upvotes: 1

Views: 50

Answers (3)

Hippolippo
Hippolippo

Reputation: 813

You can make a list of the length of each of the lengths using list comprehension and then get the sum of it and divide that by the length:

average = sum([len(x) for x in sentences])/len(sentences)

Then you can iterate through the list and remove sentences over that limit

sentences = [sentence for sentence in sentences if len(sentence) > average]

Upvotes: 1

GLarose
GLarose

Reputation: 171

Try making a new list of just those sentences with length greater than mean sentence length in original list

new_sentence_list = []
for i in original_sentence_list:
   if len(i) > mean(len(i) for i in original_sentence_list):
     new_sentence_list.append(i)

Upvotes: 0

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 2914

You can use sum() and list comprehension for this

avg_len = sum(len(str) for str in strings) / len(strings)
filtered = [str for str in strings if len(str) >= avg_len]

Notice that the / operator returns a floating point and that you might want to round it based on your preference.

Upvotes: 3

Related Questions