Skip to content Skip to sidebar Skip to footer

Sort Strings By The First N Characters

I have a text file with lines like this: 2010-02-18 11:46:46.1287 bla 2010-02-18 11:46:46.1333 foo 2010-02-18 11:46:46.1333 bar 2010-02-18 11:46:46.1467 bla A simple sort would sw

Solution 1:

sorted(array, key=lambda x:x[:24])

Example:

>>> a = ["wxyz", "abce", "abcd", "bcde"]
>>> sorted(a)
['abcd', 'abce', 'bcde', 'wxyz']
>>> sorted(a, key=lambda x:x[:3])
['abce', 'abcd', 'bcde', 'wxyz']

Solution 2:

The built-in sort is stable, so you the effectively-equal values stay in order by default.

import operator

withopen('filename', 'r') as f:
    sorted_lines = sorted(f, key=operator.itemgetter(slice(0, 24)))

At this point sorted_lines will be a list of the sorted lines. To replace the old file, make a new file, call new_file.writelines(sorted_lines), then move the new file over the old one.

Post a Comment for "Sort Strings By The First N Characters"