本文介绍了将月份名称字符串列表按升序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以指导如何排序月份列表吗?
Can someone please guide how to sort list of months?
INPUT = ['August', 'September', 'October', 'November', 'December', 'January'] OUTPUT= ['January','August', 'September', 'October', 'November', 'December'] 推荐答案calendar.month_name 是按正确顺序排列的月份数组.假设您输入的字符串格式正确,您可以按此列表中每个字符串的索引进行排序:
calendar.month_name is an array of months in the correct sequence. You can sort by the index of each string in this list, assuming your input strings are well-formed:
>>> from calendar import month_name >>> months = ['August', 'September', 'October', 'November', 'December', 'January'] >>> month_lookup = list(month_name) >>> sorted(months, key=month_lookup.index) ['January', 'August', 'September', 'October', 'November', 'December']您还可以使用 datetime.strptime 和与完整月份名称匹配的%B" 格式字符串.
You can also use datetime.strptime and the "%B" format string which matches the full month name.
>>> from datetime import datetime >>> months = ['August', 'September', 'October', 'November', 'December', 'January'] >>> sorted(months, key=lambda m: datetime.strptime(m, "%B")) ['January', 'August', 'September', 'October', 'November', 'December']请注意,两种解决方案都会在包含无效月份字符串的列表上引发错误.
Note that both solutions raise errors on lists containing invalid month strings.
更多推荐
将月份名称字符串列表按升序排序
发布评论