Reputation:
If I have a list of strings, how would I sort it alphabetically by ignoring vowels. For example, ['alpha', 'beta'] would sort to ['beta', 'alpha'], because 'bt' is alphabetically before 'lph'. I've tried it a bit using lambda functions and stuff, but I am a bit stuck, any help would be appreciated.
Upvotes: 2
Views: 989
Reputation: 48090
In Python 2.x, you may use string.translate()
within lambda to remove the vowels from the string as:
>>> my_list = ['alpha', 'beta', 'gamma', 'theta']
>>> vowels = 'aeiouAEIOU' # string of 'vowel'
>>> sorted(my_list, key=lambda s: s.translate(None, vowels))
['beta', 'gamma', 'alpha', 'theta']
But in Python 3.x, you need to firstly convert the string to byte in order to access the translate
function. for example:
sorted(my_list, key=lambda s: s.encode.translate(None, b'aeiouAEIOU')
# Note: This will work on Python 2.x as well, but encoding is not required there
As an alternative, you also use the below lambda expression within the sorted
which will work fine on both Python 2.x and 3.x:
sorted(my_list, key=lambda s: ''.join(c for c in s if c not in vowels))
Upvotes: 2
Reputation: 304375
It's a good idea to use a named function here. There are two benefits - you can use a descriptive name, and you've got a function that can be unit tested.
def remove_vowels_from_string(s):
return s.translate(None, 'aeiouAEIOU')
new_list = sorted(my_list, key=remove_vowels_from_string)
For Python3, you can use this version
def remove_vowels_from_string(s):
return translate(dict.fromkeys(map(ord, 'aeiouAEIOU')))
new_list = sorted(my_list, key=remove_vowels_from_string)
Upvotes: 1
Reputation: 6475
You can use a lambda function in the key parameter of sorted function.
In [14]: l = ['alpha', 'beta']
In [15]: v = {'a', 'e', 'i', 'o', 'u'}
In [16]: sorted(l, key=lambda item: [char for char in item if char.lower() not in v])
Out[16]: ['beta', 'alpha']
Upvotes: 3