[Tutor] Sorting a list
Ataulla S H
ataulla at gmail.com
Wed May 13 19:42:29 CEST 2009
>>> l = [4, 6, 'word','a', 3, 9]
>>> l.sort()
>>> l
[3, 4, 6, 9, 'a', 'word']
>>> k = [each for each in l if type(each) == type(int())]
>>> k
[3, 4, 6, 9]
>>> kex = [each for each in l if type(each) != type(int())]
>>> kex
['a', 'word']
>>> kex+k
['a', 'word', 3, 4, 6, 9]
On Wed, May 13, 2009 at 10:55 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "vince spicer" <vinces1979 at gmail.com> wrote
>>
>> def compare(x,y):
>> try:
>> return cmp(int(x), int(y))
>> except:
>> pass
>> try:
>> int(x)
>> except:
>> return -1
>> try:
>> int(y)
>> except:
>> return 1
>> return 0
>
> Or
>
> 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...
>
>
>>>> L = [4,3,'word','picture',1,2,3]
>>>> sorted(L, cmp=comp)
>
> ['picture', 'word', 1, 2, 3, 3, 4]
>>>>
>>>> L = [4,3,'picture','word',1,2,3]
>>>> sorted(L, cmp=comp)
>
> ['word', 'picture', 1, 2, 3, 3, 4]
>
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Ataulla SH
web:www.kring.com
personal blog:www.ataulla.objectis.net
KRING Technologies India Pvt. Ltd.
1st Floor, Tower B, Infinity Towers, DLF II, Gurgaon-122 002
More information about the Tutor
mailing list