按前 N 个字符对字符串进行排序 [英] Sort strings by the first N characters
本文介绍了按前 N 个字符对字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的文本文件:
2010-02-18 11:46:46.1287 bla2010-02-18 11:46:46.1333 foo2010-02-18 11:46:46.1333 吧2010-02-18 11:46:46.1467 bla
一个简单的排序会交换第 2 行和第 3 行(bar 在 foo 之前),但我想保留行(具有相同日期/时间)的原始顺序.
如何在 Python 中执行此操作?
解决方案
sorted(array, key=lambda x:x[:24])
示例:
<预><代码>>>>a = ["wxyz", "abce", "abcd", "bcde"]>>>排序(一)['abcd', 'abce', 'bcde', 'wxyz']>>>sorted(a, key=lambda x:x[:3])['abce', 'abcd', 'bcde', 'wxyz']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?
解决方案
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']
这篇关于按前 N 个字符对字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文