自定义排序 python 中的列表

Custom sorting a list in python

我想对以下列表进行排序,其中一些元素是日期,一些是宿舍。

input_ls = ['Nov-2015', 'Quarter 1, 2016', 'Jan-2016', 'Dec-2015',
           'Feb-2016', 'Quarter 4, 2015']

预期输出如下。我该怎么做?

output_ls = ['Quarter 1, 2016', 'Feb-2016', 'Jan-2016', 'Quarter 4, 2015'
             'Dec-2015', 'Nov-2015']

问题更改后的新答案:

您需要将日历月和季度映射到数字以满足您的预期输出。一个例子可以是:

mapping = {'Jan':1, 'Feb':2, .. 'Quarter 1':4, .. }

然后迭代列表,解析每个条目并将其映射到一个数字进行排序。

i_map = {}
for i in input_ls:
    # for 'Nov-2015' format
    i1 = i.split('-')
    if len(i1) == 1:
        # For 'Quarter 1, 2015' format
        i1 = i.split(',')

    # Now map it to a number for sorting 
    i_map[mapping[i1[0]]] = i

# Now sort i_map by key
i_map_sorted = sorted(i_map, key=lambda (k,v) : k) 

# Now you can iterate over the sorted object & print its values

问题更改前的旧答案:

如果您想为字典自定义排序顺序,可以使用像这样的 lambda 函数

sorted(input_dic.items(), key=lambda (key,value) : <fn of key & value>) 

你能用伪代码指定逻辑顺序吗?

要颠倒顺序,在上面的函数中加入reverse=True

如果您只想对值进行排序,则遍历字典并分别对它们进行排序,例如

from collections import OrderedDict
new_dict = OrderedDict()
for k,v in mydict.items():
    new_dict[k] = sorted(v, key=<some fn>, reverse=True)

如果您想按日历月份值(而不是按字母顺序排列的名称)排序,您需要在自定义排序函数中进行查找以将月份映射到数字,例如{'Jan':1, 'Feb':2, ...}

P.S。 sorted fn 的输出将是一个元组。正如上面的评论所指出的,如果你想保留字典结构,请使用 OrderedDict。

这是一个使用 datetutil and regex 的解决方案:

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()

这就是输出的样子:

这是另一种使用排序键的方法,可能是最 pythonic 的方法——在 Martijn Pieters

的帮助下
from dateutil import parser
import re
input_ls = ['Nov-2015', 'Quarter 1, 2016', 'Jan-2016', 'Dec-2015','Feb-2016', 'Quarter 4, 2015']

def sort_key(x):
    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:
        return parse('1,' + x)
    #If matching then format it to a string format that is acceptable to the dateutil parser
    else:
        return parse(str(int(qtr[0][0])*3)+'-30-'+qtr[0][1])

input_ls.sort(key=sort_key)

这就是输出的样子: