代码之家  ›  专栏  ›  技术社区  ›  compie Artelius

对文本文件中的行进行排序,但只使用前n个字符

  •  9
  • compie Artelius  · 技术社区  · 15 年前

    我有一个文本文件,上面有这样的行:

    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
    

    一个简单的排序将交换第2行和第3行(bar在foo之前),但我希望保持行(具有相同的日期/时间)的原始顺序。

    我怎样才能在python中做到这一点?

    额外的问题:GNU排序也可以这样做吗?

    2 回复  |  直到 15 年前
        1
  •  24
  •   kennytm    15 年前
    sorted(array, key=lambda x:x[:24])
    

    >>> a = ["wxyz", "abce", "abcd", "bcde"]
    >>> sorted(a)
    ['abcd', 'abce', 'bcde', 'wxyz']
    >>> sorted(a, key=lambda x:x[:3])
    ['abce', 'abcd', 'bcde', 'wxyz']
    
        2
  •  5
  •   Mike Graham    15 年前

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

    sorted_lines new_file.writelines(sorted_lines)