Sorting a list based on number of vowels in the words in python

Question:

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.

Asked By: yashwanth

||

Answers:

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']
Answered By: falsetru

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)
Answered By: shiva vanka
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)
Answered By: kouwkik
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.