Reputation: 5
How do I sort a list based on number of vowels in the words in python?
I have not found the answer on any website. The word should be in descending order of number of vowels.
Upvotes: 0
Views: 6351
Reputation: 1
def count(word):
a = "aeiouAEIOU"
return sum(c in a for c in word)
def sort_strings(string):
return sorted(string, key=count)
if __name__ == "__main__":
string = ['age', 'beware', 'aid', 'airport', 'bike']
sorted_strings = sort_strings(string)`enter code here`
print(sorted_strings)
Upvotes: -1
Reputation: 1
you can do it by creating two functions as follows
def vowel_count_test(string):
count=0
for z in string:
if z in ['a','e','i','o','u']:
count=count+1
return count
def sort_by_vowel_count(words):
return words.sort(key=vowel_count_test,reverse=True)
Upvotes: 0
Reputation: 369324
Use sorted
or list.sort
.
Specify key
with function that count the number of vowels. (The return value of the function is used as comparison key.)
Pass reverse=True
argument to order descending.
>>> word_list = ['banana', 'apple', 'pineapple']
>>> sorted(word_list,
... key=lambda word: sum(ch in 'aeiou' for ch in word),
... reverse=True)
['pineapple', 'banana', 'apple']
Upvotes: 5