按数字和按月名称排序

时间:2015-01-22 07:30:56

标签: python sorting dictionary built-in

我有一个功能需要3个不同的输入:

以下形式的天数:

"Day 2":Something,
"Day 1":Something,
"Day 3":Something,
"Day 5":Something,
"Day 4":Something

几周的决定:

"Week 2":Something,
"Week 1":Something,
"Week 4":Something,   
"Week 3":Something,
"Week 5":Something

几个月的词典:

"April":Something,
"February":Something,
"March":Something,
"January":Something

因为它们是决定性的,所以它们是无序的。我操纵它们以有序的方式呈现给用户。

我正在寻找一种方法来拆分sorted()内置来处理这三种类型。

输出应该是按数字(天/周)和按月分类的键:

"Day 1"
"Day 2"
"Day 3"
"Day 4"
"Day 5"
###
"Week 1"
"Week 2"
"Week 3"
"Week 4"
"Week 5"
###
"January"
"February"
"March"
"April"

我知道我可以使用三元操作:

sorted(input_dict, key=lambda x: int(x.strip("Day ")) if "Day 1" in input_dict else sorted(input_dict, key=lambda x: int(x.strip("Week ")) if "Week 1" in input_dict else sorted...

但它变得非常混乱。

我正在寻找如何使用已定义的函数实现键函数。

类似的东西:

def my_sort_function():
    # magic goes here

for n in sorted(input_dict, key=my_function):
    pass

1 个答案:

答案 0 :(得分:2)

所以...对您的日/周列表进行排序非常简单:

def sort_day_week_key(day_week_str):
    return int(day_week_str.split()[-1])

但你想要处理几个月。显而易见的解决方案是将月份名称映射到数字:

import calendar
_MONTH_MAP = {m.lower(): i for i, m in enumerate(calendar.month_name[1:])}
def sort_month_names_key(m_name):
    return _MONTH_MAP[m_name.lower()]

现在您只想将这两个功能结合起来。这很简单:try一个,如果它没有工作则使用另一个:

def sort_the_stuff_key(item):
    try:
        return sort_month_names_key(item)
    except KeyError:
        return sort_day_week_key

def sort_the_stuff(some_iterable):
    return sorted(some_iterable, key=sort_the_stuff_key)

当然,如果你的iterable中有多个字符串类的项目(例如日期和月份名称),这种排序函数会产生奇怪的结果,但听起来好像不会发生......