I’m supposed to take a list of words and sort it, except I need to group all Strings that begin with ‘x’ first.
Here’s what I got:
list_1 = []
list_2 = []
for word in words:
list_1.append(word) if word[0] == 'x' else list_2.append(word)
return sorted(list_1) + sorted(list_2)
But I have a feeling there is a much more elegant way to do this…
EDIT
Example:
['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'].
Explanation: the key function returns a pair (tuple). The first element is
FalseorTrue, depending on whether the first char in the string is'x'.Falsesorts beforeTrue, so strings starting with'x'will be first in the sorted output. The second element in the tuple will be used to compare two elements that are the same in the first element, so all the strings starting with'x'will be sorted amongst themselves, and all the strings not starting with'x'will be sorted amongst themselves.