outline-style sorting algorithm

Fredrik Lundh fredrik at pythonware.com
Tue Apr 20 09:59:09 EDT 2004


Michael Geary wrote:

> It seems like a simple enough algorithm: Split each filename into groups of
> numbers and non-numbers. When you do a sort comparison, take these character
> groups from left to right, comparing the non-numeric parts alphabetically
> and the numeric parts numerically.

import re

def split(name, findall=re.compile("(\d+)|(\D+)").findall):
    parts = []
    for d, s in findall(name):
        if d:
            s = int(d)
        parts.append(s)
    return parts

(preferrably combined with DSU, but if you don't have too many
files, you can use sort(lambda a, b: cmp(split(a), split(b))))

</F>







More information about the Python-list mailing list