我必须根据月份名称:
对字符串列表进行排序my_list = ['apple_april', 'banana_july', 'carrot_december', 'dog_january']
我必须在1月,2月,马丁之前排序,.....
我的试用版:
months = [m.split('_')[1] for m in my_list]
ans = [x for (y,x) in sorted(zip(months,my_list))]
但没有成功,你会怎么做?
预期的答案是:
['dog_january', 'apple_april', 'banana_july', 'carrot_december']
答案 0 :(得分:3)
list.sort
,sorted
接受可选的key
参数。传递一个将相应数字返回到monthes的键函数。
>>> import calendar
>>>
>>> months = {calendar.month_name[i].lower(): i for i in range(1, 12+1)}
>>> my_list = ['apple_april', 'banana_july', 'carrot_december', 'dog_january']
>>> sorted(my_list, key=lambda x: months[x.split('_')[1]])
['dog_january', 'apple_april', 'banana_july', 'carrot_december']
months
使用calendar.month_name
:
>>> months
{'april': 4, 'november': 11, 'june': 6, 'august': 8, 'december': 12, 'october': 10,
'july': 7, 'march': 3, 'september':9, 'may': 5, 'january': 1, 'february': 2}
答案 1 :(得分:2)
您可以在日历中制作月份字典及其对应的位置:
months = {'january': 1,
'april': 4,
'july': 7,
'december': 12}
然后通过在字典中查找月份来对列表进行排序。首先在下划线上拆分列表的每个元素(它给出一个列表,如['dog', 'january']
),然后使用months.get
在字典中查找此列表的最后一个元素:
>>> sorted(my_list, key=lambda x: months.get(x.split('_')[-1]))
['dog_january', 'apple_april', 'banana_july', 'carrot_december']
修改强>:
如果你安装了dateutil
,那就太懒了......
>>> import dateutil
>>> sorted(my_list, key=lambda x: dateutil.parser.parse(x.split('_')[-1]))
['dog_january', 'apple_april', 'banana_july', 'carrot_december']
不需要字典! dateutil.parser.parse
将月份字符串解析为datetime
对象。
答案 2 :(得分:2)
>>> from datetime import datetime
>>> my_list = ['apple_april', 'banana_july', 'carrot_december', 'dog_january']
>>> sorted(my_list, key=lambda x: datetime.strptime(x.split('_')[1], '%B'))
['dog_january', 'apple_april', 'banana_july', 'carrot_december']
答案 3 :(得分:1)
您可以根据calendar.month_name
或calendar.month_abbr
>>> import calendar
>>> m=list(calendar.month_abbr)
>>> l=[(i,x) for x in my_list for i,j in enumerate(m) if j==x.split('_')[1][:3]]
>>> [i[1] for i in sorted(l,key= lambda x: x[0])]
['dog_january', 'apple_april', 'banana_july', 'carrot_december']