Reputation:
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
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
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
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