使用列表中包含的特定字符串对一个列表进行排序

时间:2014-12-21 10:14:50

标签: python list sorting

我必须根据月份名称

对字符串列表进行排序
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']

4 个答案:

答案 0 :(得分:3)

list.sortsorted接受可选的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_namecalendar.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']