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?
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With