can't sort
Anders J. Munch
andersjm at dancontrol.dk
Thu May 22 13:01:54 EDT 2003
"John Roth" wrote:
> I think Ruby handles this situation better than Python,
> frankly. According to reports, Ruby has two methods that
> correspond to [].sort(). One is [].sort(), and the other is
> [].sort!(). (Note the !). The first returns what you would
> naturally expect: a new object without modifying the original
> object. The second returns the original object after modifying
> it.
>
> So far, this doesn't seem to have gotten high enough on
> anyone's irritation list for them to have suggested a solution
> that's both Pythonic and backward compatible.
It's fairly high on my irritation list. In my usage a functional sort
is more convenient and fast enough about 10 out of 9 times.
Suppose we added the following function to the builtins. Or at least,
to a standard module.
def sort(sequence, cmpfunc=None, project=None):
"""sort a sequence, returning a new list;
if given, cmpfunc(x,y) -> -1, 0, 1;
if given, sequence is sorted as would be [project(x) for x in sequence]"""
if cmpfunc is not None:
assert project is None
sorted = list(sequence)
sorted.sort(cmpfunc)
elif project is not None:
intermed = [(project(val), no, val)
for (no,val) in enumerate(sequence)]
intermed.sort()
return [elem[2] for elem in intermed]
else:
sorted = list(sequence)
sorted.sort()
return sorted
This function sorts arbitrary sequences (presuming enumerate works for
unsized sequences, haven't tried out 2.3 so I don't know for sure),
and always returns a new list.
For good measure it also implements the DSU pattern if you provide a
projection function.
gør-som-10-ud-af-9-det-er-demokrati-ly y'rs, Anders
More information about the Python-list
mailing list