[Tutor] Sorting a list
Kent Johnson
kent37 at tds.net
Thu May 14 16:23:56 CEST 2009
On Thu, May 14, 2009 at 9:13 AM, Lie Ryan <lie.1296 at gmail.com> wrote:
> Why not:
>>>> sorted(lst, key=lambda x: (0, x) if isinstance(x, str) else (1, x))
> ['word', 3, 4, 6, 9]
>
> I think sorting tuple has a well-defined meaning, i.e. sort on first item,
> then second, then third, etc... and there is AFAIK no restriction that the
> key argument should be a number right?
Right. Tuples sort lexicographically (which is a fancy way to say sort
on first item, etc) and the key values just have to be comparable.
This is a very clean simple solution.
Kent
More information about the Tutor
mailing list