0

I have the following two dimensional array:

arr = [
["A", "B", "C", "10.03.2030", "14:06"],
["W", "R", "Q", "09.04.2025", "12:06"],
["Y", "X", "V", "11.05.2022", "12:06"],
["Z", "N", "H", "10.03.2030", "14:06"],
]

I want to sort the array by & time, is there a fast way to do that in python?

thanks in advance

andy

moestly
  • 1,681
  • 15
  • 19
Andy
  • 51
  • 9
  • 3
    I deleted my answer because it was actually wrong. But to answer your question about being downvoted: I didn't downvote (not did I upvote) your question, but those who did likely did so because 1) you haven't shown any effort at accomplishing this yourself and 2) this is not a new problem and could easily be solved with some effort Googling. Good luck. – blacksite Oct 05 '17 at 16:29

3 Answers3

5

You can sort by first transforming the dates into ISO8601 format (as opposed to transforming to actual dates with datetime.strptime which is pretty slow) and then break ties using the already standardised time string:

lst = sorted(arr, key=lambda x: (x[3].split('.')[::-1], x[-1]))
print(lst)

x[3].split('.')[::-1] builds a list of the ISO date from the original date string, bringing the year first, month next and then date.


[['Y', 'X', 'V', '11.05.2022', '12:06'],
 ['W', 'R', 'Q', '09.04.2025', '12:06'],
 ['A', 'B', 'C', '10.03.2030', '14:06'],
 ['Z', 'N', 'H', '10.03.2030', '14:06']]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • thank you so much, your answer was the best, for date and time, all other solutions sort only by date and not the time too. I want to ask you something, can you please explain this part: (x[3].split('.')[::-1], x[-1], this will take the date and split it by (dot), for first one ['2022', '05', '11'] and I dont understand why negative number -1 and not 2 ? and also the x[-1] Please... – Andy Oct 23 '17 at 20:26
0

As mentioned in this answer, you should use itemgetter for this purpose.

To sort your data by time, use this:

from operator import itemgetter
print(sorted(arr, key=itemgetter(4)))
[['W', 'R', 'Q', '09.04.2025', '12:06'], 
['Y', 'X', 'V', '11.05.2022', '12:06'], 
['A', 'B', 'C', '10.03.2030', '14:06'], 
['Z', 'N', 'H', '10.03.2030', '14:06']]

If you need to sort by date (year), you need to define a separate function or use a lamda. I have written both solutions:

def sorting(item):
    return item[3].split('.')[2]

print(sorted(arr, key=sorting))

# using lambda
print(sorted(arr, key= lambda item:item[3].split('.')[2]))

[['Y', 'X', 'V', '11.05.2022', '12:06'], 
['W', 'R', 'Q', '09.04.2025', '12:06'], 
['A', 'B', 'C', '10.03.2030', '14:06'], 
['Z', 'N', 'H', '10.03.2030', '14:06']]

This way you don't rely on a third party package import.

Adeel Ahmad
  • 1,033
  • 1
  • 11
  • 24
0

very short and neat code than others given above

lst = sorted(arr, key=lambda x: (x[3].split('.')[::-1], x[-1]))
Argus Malware
  • 773
  • 7
  • 19