按数字和月份名称排序
Sorting Numericly and by Month name
我有一个函数需要 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() 来处理这三种类型。
输出应该是按数字(days/week)和按月排序的键:
"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
所以...对 days/weeks 的列表进行排序非常简单:
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)
当然,如果您的可迭代对象包含来自多个 class 字符串的项目(例如,日期和月份名称),则此排序函数会给出奇怪的结果,但听起来不会发生...
我有一个函数需要 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() 来处理这三种类型。
输出应该是按数字(days/week)和按月排序的键:
"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
所以...对 days/weeks 的列表进行排序非常简单:
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)
当然,如果您的可迭代对象包含来自多个 class 字符串的项目(例如,日期和月份名称),则此排序函数会给出奇怪的结果,但听起来不会发生...