Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

python - 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...