Sort week day texts

对着背影说爱祢 提交于 2020-01-13 05:38:19

问题


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?


回答1:


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




回答2:


http://wiki.python.org/moin/HowTo/Sorting/

You are looking for a lexical sort. It’s also interesting to write your own function, as a learn matter ;)

EDIT: ok you just need a function that, for a day, returns its day week number. You can simply use an array of day string in the function, and then use the day week number to sort elements like a boss.




回答3:


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



来源:https://stackoverflow.com/questions/13844158/sort-week-day-texts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!