[Tutor] samples on sort method of sequence object.

Stefan Behnel stefan_ml at behnel.de
Wed Jan 13 14:13:24 CET 2010


Albert-Jan Roskam, 13.01.2010 13:51:
> Interesting. Can this also be used to make sorting of alphanumerical list items in a 'numerical' way easier? E.g.:
>>>> x
> ['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5', 'var_6', 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10', 'var_12']
>>>> x.sort()
>>>> x
> ['var_0', 'var_1', 'var_10', 'var_11', 'var_12', 'var_13', 'var_14', 'var_2', 'var_3', 'var_4', 'var_5', 'var_6', 'var_7', 'var_8', 'var_9']
>  
> This clearly does not give the desired result. I once solved this by making a dictionary of which the keys are zfilled versions of the list items (e.g. var_01, etc), then sort the keys, get the dictionary values in the right order, etc. It seemed a cumbersome way. Isn't there an easier way to sort x?

    x.sort(key = lambda name: int(name.split('_')[-1]))

Stefan



More information about the Tutor mailing list