Help sorting a list by file extension
Tom Anderson
twic at urchin.earth.li
Fri Aug 12 06:55:58 EDT 2005
On Fri, 12 Aug 2005, Bengt Richter wrote:
> On Fri, 12 Aug 2005 00:06:17 GMT, Peter A. Schott <paschott at no.yahoo.spamm.com> wrote:
>
>> Trying to operate on a list of files similar to this:
>>
>> test.1
>> test.2
>> test.3
>>
>> I want to sort them in numeric order instead of string order.
>
> >>> [name for dec,name in sorted((int(nm.rsplit('.',1)[1]),nm) for nm in namelist)]
> ['test.1', 'test.2', 'test.3', 'test.4', 'test.10', 'test.15', 'test.20']
>
> This depends on the extension being nicely splittable with a single '.'
You could use os.path.splitext to do that more robustly:
>>> [name for dec,name in sorted((int(os.path.splitext(nm)[1][1:]),nm) for nm in namelist)]
tom
--
Everybody with a heart votes love
More information about the Python-list
mailing list