Sort strings by the first N characters

半城伤御伤魂 提交于 2021-02-04 15:08:12

问题


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 swap lines 2 and 3 (bar comes before foo), but I would like to keep lines (that have the same date/time) in their original order.

How can I do this in Python?


回答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']



回答2:


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

import operator

with open('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.



来源:https://stackoverflow.com/questions/2289870/sort-strings-by-the-first-n-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!