For this snippet, I would have probably written the more compact:
def mysort(words):
return (sorted([i for i in words if i[0] == "s"]) +
sorted([i for i in words if i[0] != "s"]))
(You're not supposed to align code like this in Python, but I tend to do it anyway.) Note that I wrote i[0]
and not i[:1]
- I think the former is clearer. Using str.startswith()
is even better.
Also, it is generally considered bad practice to use list
as a variable name.
However, your algorithm iterates the list at least three times: Once to look for the words starting with s
, once to look for the words not starting with s
and then finally O(n log n)
times more to sort the two lists. If necessary, you can improve the algorithm to do just one pass before sorting, by populating both lists simultaneously:
def prefix_priority_sort(words, special_prefix = "s"):
begins_with_special = []
not_begin_with_special = []
for word in words:
if word.startswith(special_prefix):
begins_with_special.append(word)
else:
not_begin_with_special.append(word)
return sorted(begins_with_special) + sorted(not_begin_with_special)
However, the best way is to define your own comparator and pass it to the sorting function, like mariosangiorgio
suggests. In Python 3, you need to pass in a key function, see the docs for details, or this article.
Depending on execution speed requirements, list sizes, available memory and so on, you might want to pre-allocate memory for the lists using [None] * size
. In your case it is probably premature optimization, though.