You can write your own sorted()
like so:
try:
sorted
except NameError:
def sorted(seq, key=None):
lst = list(seq) # get copy of list
if key is not None:
def my_cmp(a, b):
return cmp(key(a), key(b))
else:
my_cmp = cmp
lst.sort(my_cmp)
return lst
This will only define your new sorted()
if there is no built-in sorted()
. First, we try to evaluate the name sorted
and if we get a NameError
we define our own. I'm using map(None, seq)
as a fast way to make a new list out of the values of seq
.
Or, if we want to use the Schwartzian Transform for maximum efficiency as suggested by @gnibbler:
try:
sorted
except NameError:
import operator as op
def sorted(seq, key=None):
if key is not None:
lst = [(key(x), x) for x in seq]
lst.sort()
return map(lambda x: x[1], lst)
else:
lst = list(seq) # get list from sequence
lst.sort()
return lst