from dateutil import parser
import re
input_ls = ['Nov-2015', 'Quarter 1, 2016', 'Jan-2016', 'Dec-2015','Feb-2016', 'Quarter 4, 2015']
res = []
for x in input_ls:
#Match x if it is having a digit followed by a comma followed by a space and followed by four digits
qtr = re.findall('(\d),\s(\d{4})',x)
#If match not found parse it as date by prefixing '1,' to the string
if len(qtr) == 0:
res.append(parse('1,' + x))
#If matching then format it to a string format that is acceptable to the dateutil parser
else:
res.append(parse(str(int(qtr[0][0])*3)+'-30-'+qtr[0][1]))
#Sort the output list
out = zip(res,input_ls)
out.sort()
#Reverse it
out.reverse()
下面是一个使用^{} 和^{} 的解决方案:
输出结果如下:
这里有另一种使用排序键的方法,这可能是最具python风格的方法-在Martijn Pieters的帮助下
^{pr2}$输出结果如下:
问题更改后的新答案:
您需要一个日历月份和季度到数字的映射,以满足您的预期输出。例如:
然后迭代列表,解析每个条目并将其映射到一个数字进行排序。
^{pr2}$问题更改前的旧答案:
如果您想要一个字典的自定义排序顺序,可以使用如下lambda函数
你能在伪代码中指定逻辑顺序吗?
要颠倒顺序,请在上面的函数中添加
reverse=True
如果你只想对值进行排序,那么就遍历字典并对它们进行单独排序
^{4}$如果要按日历月份值(而不是字母名称)排序,则需要在自定义排序函数中查找以将月份映射到一个数字,例如{'Jan':1,'Feb':2,…}
另外,
sorted
fn的输出将是一个元组。正如上面的注释所指出的,如果您想保留dict结构,请使用OrderedDict。相关问题 更多 >
编程相关推荐