sort order for strings of digits

Hans Mulder hansmu at xs4all.nl
Wed Oct 31 11:31:46 EDT 2012


On 31/10/12 16:17:14, djc wrote:
> Python 3.2.3 (default, Oct 19 2012, 19:53:16)
> 
>>>> sorted(n+s)
> ['1', '10', '101', '13', '1a', '2', '2000', '222 bb', '3', '31', '40',
> 'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']
> 
>>>> sorted(int(x) if x.isdigit() else x for x in n+s)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: unorderable types: str() < int()
>>>>

>>> sorted(n+s, key=lambda x:(x.__class__.__name__, x))
['1', '10', '101', '13', '1a', '2', '2000', '222 bb', '3', '31', '40',
'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']
>>>

> The best I can think of is to split the input sequence into two lists,
> sort each and then join them.

That might well be the most readable solution.


Hope this helps,

-- HansM



More information about the Python-list mailing list