Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 847
compie Avatar asked Feb 18 '10 15:02

compie


People also ask

How do I sort characters in a string?

Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.

How do you sort a string by character in Python?

Sort a Python String with Sorted Python comes with a function, sorted() , built-in. This function takes an iterable item and sorts the elements by a given key. The default value for this key is None , which compares the elements directly. The function returns a list of all the sorted elements.


1 Answers

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']
like image 129
kennytm Avatar answered Sep 30 '22 18:09

kennytm