[Tutor] Sorting a list
bob gailer
bgailer at gmail.com
Thu May 14 15:37:47 CEST 2009
Christian Witts wrote:
> 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]
In the relentless pursuit of terseness:
>>> class L(list):
... def add(self, end, *item):self[-end:-end] = item
>>> a=[4,6,'word',3,9]
>>> result=L()
>>> [result.add(type(i) != int, i) for i in reversed(sorted(a))]
[None, None, None, None, None]
>>> result
[3, 4, 6, 9, 'word']
--
Bob Gailer
Chapel Hill NC
919-636-4239
More information about the Tutor
mailing list