[Tutor] sorting file paths made up of of strings and numbers

Kent Johnson kent37 at tds.net
Wed Apr 15 04:28:22 CEST 2009


2009/4/14 Emad Nawfal (عماد نوفل) <emadnawfal at gmail.com>:
> Hi tutors,
> How can I sort the following list in a way that takes care of the right
> order of numbers? The sorted function compares strings here as far as I can
> see, but I want to have filepath2 follow filepath1. Your help is
> appreciated.
>>>> myList
> ['filepath54', 'filepath25', 'filepath49', 'filepath0', 'filepath89',
> 'filepath52', 'filepath37', 'filepath32', 'filepath2', 'filepath15',
<snip>

The sort() and sorted() functions have an optional key= parameter. The
parameter should be a function whose argument is a list element and
whose result is the desired key. So for your list, you need a function
that creates an integer from the list item:

In [1]: myList = ['filepath54', 'filepath25', 'filepath49',
'filepath0', 'filepath89', 'filepath52', 'filepath37', 'filepath32', '
filepath2', 'filepath15']

In [2]: def index(fp): return int(fp[8:])

Now sort the list using the key:

In [3]: myList.sort(key=index)

In [4]: myList
Out[4]:
['filepath0',
 'filepath2',
 'filepath15',
 'filepath25',
 'filepath32',
 'filepath37',
 'filepath49',
 'filepath52',
 'filepath54',
 'filepath89']

Note that the key parameter takes the function object itself, there
are no parentheses. i.e. key=index, not key=index().

Kent


More information about the Tutor mailing list