NguoiMelb Ho
NguoiMelb Ho

Reputation: 1

Python: Sorting the list alphabetically ignoring vowels

Please gently with me as I am beginner. I read the answer for Sorting list of string alphabetically ignoring vowels. But I don't really understand how it sorts in this method:

l = ['alpha', 'beta']
vowels = ['aeiouAEIOU']
sorted(l, key=lambda s: ''.join(c for c in s if c not in vowels))

My questions:

  1. how can the sort can loop at the character level rather than word without splitting words?
  2. If c not vowel then join letters back to word then how they sort the words with having vowels? what happens to the other words with vowels?

Upvotes: 0

Views: 233

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522226

If I understand correctly, you want to sort the strings in your list as if they do not have vowels. So, hello should sort as hll and world should sort as wrld. You may try removing vowels in your sorting lambda:

l = ['help', 'hello', 'world', 'weld']
l = sorted(l, key=lambda s: re.sub(r'[AEIOUaeiou]', '', s))
print(l)  # ['hello', 'help', 'weld', 'world']

Upvotes: 1

Related Questions