I have the following sorting problem:
Given a list of strings, return the list of strings sorted, but group all strings starting with 'x' first.
Example: ['mix', 'banana' ,'xyz', 'apple', 'xanadu', 'aardvark'] Will return: ['xanadu', 'xyz', 'aardvark', 'apple', 'banana' ,'mix']
I solved by splitting the list into 2:
def front_x(words):
return [w for w in words if w[0] == "x"] + [w for w in words if w[0] != "x"]
Another pythonic solution for this problem would be using sorted method, like this:
def front_x(words):
return sorted(words, key=lambda x: x if x[0] == 'x' else f'y{x}')
I am having a hard time to understand what is going on after else. Any good soul to help me out? I'm grateful.