Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort week day texts

I have list ["Tue", "Wed", "Mon", "Thu", "Fri"] as list, I want to make it as ["Mon", "Tue", "Wed", "Thu", "Fri"].

How to sort this?

like image 857
Garfield Avatar asked Dec 09 '22 19:12

Garfield


2 Answers

Not very efficient, but if you have a list of the order they're supposed to be in...

>>> m = ["Mon", "Tue", "Wed", "Thu", "Fri"]
>>> n = ["Tue", "Wed", "Mon", "Thu", "Fri", "Tue", "Mon", "Fri"]
>>> sorted(n, key=m.index)
['Mon', 'Mon', 'Tue', 'Tue', 'Wed', 'Thu', 'Fri', 'Fri']

Note, this will throw an exception if a certain value is present in n that isn't in m.

Or put them into a dict with name as key and order as value, then use key=your_dict.get as a key... something like:

>>> d = {name:val for val, name in enumerate(m)}
>>> d
{'Fri': 4, 'Thu': 3, 'Wed': 2, 'Mon': 0, 'Tue': 1}
>>> sorted(n, key=d.get)
['Mon', 'Mon', 'Tue', 'Tue', 'Wed', 'Thu', 'Fri', 'Fri']

This won't throw an exception (except on Py3.x where you'll get an error on trying to sort None), but you could use a partial to sensible, sort before or after default, or to get equivalent behaviour of list.index, use key=d.__getitem__ or similar

like image 51
Jon Clements Avatar answered Dec 11 '22 07:12

Jon Clements


Find and replace all instances of monday with 1, tuesday with 2, etc sort, reassign.

like image 24
VoronoiPotato Avatar answered Dec 11 '22 08:12

VoronoiPotato