sorting strings written to files

Peter Hansen peter at engcorp.com
Wed Apr 9 08:40:37 EDT 2003


Max M wrote:
> 
> This could give problems:
> 
> l.sort()
> print l
>  >>> ['a\ta', 'a\tad', 'a\tb', 'a\tbe', 'a\tc', 'a\tcf', 'aa\ta',
>   'ab\tb', 'ac\tc', 'ad\tad', 'ae\tbe', 'af\tcf']
> 
> You would need to split them on the '\t' first.
> 
> # decorate sort undecorate
> l2 = [i.split('\t')[:2] + [i] for i in l]
> l2.sort()
> sorted = [i[-1] for i in l2]
> print sorted
> 
>  >>> ['a\ta', 'a\tad', 'a\tb', 'a\tbe', 'a\tc', 'a\tcf', 'aa\ta',
> 'ab\tb', 'ac\tc', 'ad\tad', 'ae\tbe', 'af\tcf']

Uh.... is there supposed to be some difference between your two
output lists?  

Given the problem as described, William's solution was quite adequate.

-Peter




More information about the Python-list mailing list