this customize sort did not work ,what's wrong?

Stephen Hansen apt.shansen at gmail.com
Sat Jan 23 22:14:47 EST 2010


On Sat, Jan 23, 2010 at 12:57 PM, thinke365 <thinke365 at gmail.com> wrote:

> def sort_by_list(E1, E2):
>    print len(E1), len(E2)
>    return len(list(E1)) > len(list(E2))
>
> l.sort(cmp=sort_by_list)
>

The cmp function is defined as returning one of three values, -1, 0 and 1.

You are returning true or false, so things aren't getting sorted because
you're not giving cmp what it is looking for. You could rewrite that as
return cmp(len(list(E1)), len(list(E2))) if you want. However, cmp is going
away in Py3.

You can just do, instead:

l.sort(key=len)

And you'll get precisely what you're looking for.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100123/cd6e076d/attachment-0001.html>


More information about the Python-list mailing list