将月份名称字符串列表按升序排序

编程入门 行业动态 更新时间:2024-10-26 00:26:17
本文介绍了将月份名称字符串列表按升序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人可以指导如何排序月份列表吗?

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.

更多推荐

将月份名称字符串列表按升序排序

本文发布于:2023-10-18 03:21:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502927.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:升序   字符串   名称   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!