[Tutor] Sorting a list
Christian Witts
cwitts at compuscan.co.za
Thu May 14 12:24:15 CEST 2009
Kent Johnson wrote:
> On Thu, May 14, 2009 at 3:34 AM, Timo <timomlists at gmail.com> wrote:
>
>> Emile van Sebille schreef:
>>
>
>
>>> If this is always the case you can use the sort method of lists, then
>>> relocate the last entry to the front --
>>>
>>>
>>>>>> a = [4, 6, 'word', 3, 9]
>>>>>> a.sort()
>>>>>> a.insert(0,a.pop())
>>>>>> a
>>>>>>
>>> ['word', 3, 4, 6, 9]
>>>
>> Thanks all for your answers. I think I will go for this solution (should
>> have come to it myself).
>>
>
> I don't think this will be reliable. IIUC unlike objects are compared
> by ID, so it is not guaranteed that strings will sort after numbers.
> The ability to compare unlike objects at all is considered a
> mis-feature and has been removed in Python 3:
> http://mail.python.org/pipermail/python-dev/2004-June/045111.html
>
> Python 3.0.1 (r301:69556, Feb 14 2009, 22:08:17)
> [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>
>
>>>> a = [4, 6, 'word', 3, 9]
>>>> a.sort()
>>>>
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: unorderable types: str() < int()
>
> Kent
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
Why not be safe and generate 2 lists and merge them afterwards like:
>>> numeric_list, string_list = [], []
>>> a=[4,6,'word',3,9]
>>> [numeric_list.append(int(element)) if element.isdigit() else
string_list.append(element) for element in map(str,a)]
[None, None, None, None, None]
>>> numeric_list.sort(); string_list.sort();
>>> numeric_list, string_list
([3, 4, 6, 9], ['word'])
>>> string_list.extend(numeric_list)
>>> string_list
['word', 3, 4, 6, 9]
--
Kind Regards,
Christian Witts
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090514/45887823/attachment.htm>
More information about the Tutor
mailing list