[Tutor] Sorting a list
Kent Johnson
kent37 at tds.net
Thu May 14 15:20:41 CEST 2009
On Wed, May 13, 2009 at 1:25 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> def compare(x,y):
> if type(x) == str: return -1
> if type(y) == str: return 1
> return cmp(x,y)
>
>
> Runs into problems if you have multiple strings and want them sorted too...
A slight variation - if the types are the same, use cmp():
In [1]: def compare(x, y):
...: if type(x) == type(y):
...: return cmp(x, y)
...: if type(x) == str: return -1
...: if type(y) == str: return 1
...: return cmp(x, y) # This is kind of arbitrary
...:
In [2]: L = [4,3,'word','picture',1,2,3]
In [3]: sorted(L, cmp=compare)
Out[3]: ['picture', 'word', 1, 2, 3, 3, 4]
In [4]: L = [4,3,'picture','word',1,2,3]
In [5]: sorted(L, cmp=compare)
Out[5]: ['picture', 'word', 1, 2, 3, 3, 4]
Kent
More information about the Tutor
mailing list